Showing posts with label Code First. Show all posts
Showing posts with label Code First. Show all posts

Friday, 15 May 2015

Setting Up One to Many Relationship with Fluent API in Code First

Let's say that we would like to have a one to many relationship between two tables, e.g. User and Article. A User can have many Articles. Below are two ways of how we could specify the models and relationship configuration with Fluent API.

1. Without Having Foreign Key Property in Model
public class Article 
{
 public int Id { get; set; }

 [StringLength(150)]
 [Required]
 public string Title { get; set; }

 [Required]
 public string Description { get; set; }

 [StringLength(500)]
 [Required]
 public string Url { get; set; }

 #region navigation properties
 public virtual User Submitter { get; set; }
 #endregion
}


public class User 
{
 public int Id { get; set; }
 
 [StringLength(100)]
 [Required]
 public string Firstname { get; set; }
 
 [StringLength(100)]
 [Required]
 public string Lastname { get; set; }

 #region navigational property
 public virtual ICollection<Article> Articles { get; set; }
 #endregion
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
 #region Article table
 modelBuilder.Entity<Article>().HasKey(t => t.Id);
 // specify the relationship between the two tables
 modelBuilder.Entity<Article>().HasRequired(t => t.Submitter).WithMany(t => t.Articles);
 #endregion

 #region User table
 modelBuilder.Entity<User>().HasKey(t => t.Id);
 #endregion
}
Before we go further, I would like to say that I prefer to use Data Annotation attributes in a model for validation purpose only for its properties. The database related configurations are done inside OnModelCreating() method.

On the codes above, we do not specify any foreign key property such as 'SubmitterId'. We do this purely in 'code first perspective' only which focuses on models and 'code' relationships between them, not their relational database relationships. So we do not worry on specifying any foreign key property here, we only specify the navigational property.

Please note as well that we do not put a [Required] attribute on the navigation property even though we always want this model to have a navigational property object (i.e. an article must have a submitter). This would create an issue for us later when we want to update an article object only without worrying about submitter. It is better to specify this rule when specifying the relationship in Fluent API.

To let Code First know the relationship we want, we put this on OnModelCreating() method:
modelBuilder.Entity<Article>().HasRequired(t => t.Submitter).WithMany(t => t.Articles);
The validation rule that the navigational property (i.e. submitter) is required is set here.

Code First will generate tables like below:



2. With Foreign Key Property in Model
If we prefer to specify foreign key property in our model, then we can do this way:
// add foreign key property to the model (Article)
public int SubmitterId { get; set; }
The advantage of doing it this way is that we can name it with any name we like.

Then on OnModelCreating() method, we write:
modelBuilder.Entity<Article>().HasRequired(t => t.Submitter).WithMany(t => t.Articles).HasForeignKey(t => t.SubmitterId);

Below are the tables and columns that will be generated:



For setting other configurations using fluent API, please see this post.

Tuesday, 24 December 2013

Enabling Automatic Code First Migration

This post is describing how to set automatic Entity Framework Code Fist migration, for the manual migration please see my previous post.

Automatic Code First migration feature is useful during development phase when database has not gone into production environment yet.

If you haven't got an EF migration Configuration.cs file then you can run this command on Package Manager Console:
Enable-Migrations –EnableAutomaticMigrations
This will add a folder called 'Migrations' in the project and a file called Configuration.cs with this setting in the constructor method:
AutomaticMigrationsEnabled = true;

If you have already got the file, make sure that AutomaticMigrationsEnabled property setting is set to true in the constructor.

Secondly, ensure that MigrateDatabaseToLatestVersion initialisation option is set on the project startup file (for example; inside global.asax)
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
DatabaseContext: your database context class name
Configuration: this is the Configuration file discussed earlier. You would need to make the class to be public if you put the initialiser inside other project.

Also if we want the automatic migration to allow data loss (for example; allowing column to be removed) then AutomaticMigrationDataLossAllowed property would need to be set to true.

So the constructor will have these settings:
public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

Monday, 23 December 2013

Code First Migration

Let say we are using Entity Framework Code First for our project and have a class below:
public class Student
{
   public int StudentId { get; set; }
   public string Name { get; set; }
}
When we use the database context for the first time, the database will be created with a table called __MigrationHistory.

The table has one record initially.

To enable the migration feature, type enable-migrations on Package Manager Console. Some messages will be displayed when the command has finished running.
PM> enable-migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201312050353336_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project CodeFirstMigrationTest.
A folder called 'Migrations' with two files are created.

[timestamp]_InitialCreate.cs is created because the database has already exists when the first time we access the database context. If the database was still empty then only Configuration.cs file would be added.

There are two main commands for the migration feature:
- add-migration - add migration codes in the code layer (under 'Migrations' folder)
- update-database - update the database according to the migration codes written in the code layer

Now let's try to change our model to add a new property:
. . .
public DateTime DOB { get; set; }
. . .
Then run add-migration command to add the change:
PM> add-migration addDOB
Scaffolding migration 'addDOB'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration addDOB' again.
[timestamp]_addDOB.cs file is created.


Now try update-database command to apply the changes to the database:
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201312081946270_addDOB].
Applying explicit migration: 201312081946270_addDOB.
Running Seed method.

Then check __MigrationHistory table again. As we can see, a new record is created in the table with Id value the same as the name of the newly generated file.


If necessary, we could customise the codes in the file generated by the add-migration command.

update-database command also has a few parameters that could be useful. We will see briefly TargetMigration, SourceMigration and Script parameters.

To upgrade/downgrade the database to a specific state, use -TargetMigration parameter. For example:
Update-Database –TargetMigration: addDOB
To roll back to empty database, use $InitialDatabase:
Update-Database –TargetMigration: $InitialDatabase

To get the changes in script only without applying those to database, use -Script parameter:
Update-Database -Script -SourceMigration: [initialState] -TargetMigration: [targetState]
If -SourceMigration is not specified then it will use the current database state. If -TargetMigration is not specified then the latest state will be assumed. For example, the command below will generate all migration scripts from empty database up to the addDOB migration state.
Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: addDOB

Starting from EF6, we could use the generated scripts to update from any previous state to the one specified as the target. The scripts have logic to check the states based on entries in __MigrationsHistory table.


Reference:
http://msdn.microsoft.com/en-us/data/jj591621.aspx

Thursday, 21 February 2013

How to Seed/Initialise Some Data in Entity Framework Code First

Entity Framework version 5.0.0 is used when writing this post.

First, we need to create a class derived from one of the built in database initialiser options' classes. They are CreateDatabaseIfNotExists, DropCreateDatabaseIfModelChanges and DropCreateDatabaseAlways. In the example below is DropCreateDatabaseIfModelChanges. I think it is possible to create a custom initialiser if we wish to do so.
public class DBInitialiser : DropCreateDatabaseIfModelChanges<MyContext>
{
    protected override void Seed(MyContext context)
    {
        // populate sizes table
        var sizes = new List<Size> {
            new Size {SizeId = 1, Code="S", Description="Small"},
            new Size {SizeId = 2, Code="M", Description="Medium"},
            new Size {SizeId = 3, Code="L", Description="Large"}
        };
        sizes.ForEach(s => context.Sizes.Add(s));       
    }
}
Notice that on line 1, we also pass the context type. Then we need to override the Seed() method and create some items to populate the database.

Next, we need to call Database.SetInitializer() method with an instance of the new derived class as its parameter when the application starts. In an MVC application, this would be inside Application_Start() in Global.asax.cs file.

If you have used Database.SetInitializer() with one of the built in database initialiser options as its parameter then you need to replace it with the new derived class' instance.
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
    // Replaced the parameter with the new derived class' instance
    Database.SetInitializer<MyContext>(new DBInitialiser());

Thursday, 15 November 2012

Some Notes about Entity Framework Code First Fluent API on Properties

- By convention a property with name 'Id' or '[Class]Id' will become the generated table primary key.

- string property will become an nvarchar(max) column.

- Keys properties and value types (any numeric, DateTime, bool and char) properties will become non-nullable columns. Reference types (String and arrays) and nullable value types (e.g.; Int16?, int?, decimal?, etc) properties will yield as nullable columns.

- byte[] property will become varbinary(max) column.

- Configuring primary key
modelBuilder.Entity<[ClassName]>().HasKey(p => p.[PropertyName]);

- Non-nullable column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsRequired();

- Nullable column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsOptional();

- Set the maximum length for a property and the generated column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).HasMaxLength([NumberLength]);

- Largest possible length of column's data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsMaxLength();

- Use fixed rather than variable data type, e.g.; varchar instead of nvarchar
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsFixedLength();
To extend the fixed data type column use
.IsFixedLength().HasMaxLength([NumberLength])
To have largest possible length of the fixed data type column use
.IsFixedLength().IsMaxLength()
For string property, we can change the default data type generated (nvarchar) to varchar by using
.IsUnicode(false)

- Use variable length data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsVariableLength();

- Specify the generated column data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).HasColumnType("[ColumnName]");

- Set the property to be used for concurrency checking
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsConcurrencyToken();

- Set a row version column in the generated table to be used as the concurrency token
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsRowVersion();
The property must have Byte[] type. IsRowVersion() is only allowed one in a class.


Further reading:
Configuring Properties and Types with the Fluent API

Friday, 2 November 2012

Get Started with Entity Framework Code First

Entity Framework version 5.0.0 is used when writing this post.

First thing we need to do is add Entity.Framework library into the project. If you are using NuGet, you can do:
PM> Install-Package EntityFramework

Then prepare your POCO classes. An example of POCO classes:
public class Stock
{
    public int StockId { get; set; }
    public int ItemId { get; set; }
    public Int16 Quantity { get; set; }
    public DateTime DateUpdated { get; set; }

    public virtual Item Item { get; set; }
}
and
public class Invoice
{
    public int InvoiceId { get; set; }
    public string Name { get; set; }    
    public string Description { get; set; }
    public decimal TotalPrice { get; set; }
    public DateTime DateSold { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateUpdated { get; set; }

    public virtual ICollection<ItemSelling> Items { get; set; }
}
To allow lazy loading, declare each navigational property as public virtual. For change tracking, declare the property as public virtual and use ICollection<T> for navigational property which contains collection. For complete details, please see this MSDN article 'Requirements for Creating POCO Proxies'

Next, create a context class that inherits from DBContext. Then specify one DBSet property for each of the POCO class that we have. If you would like to use Fluent API for configuring POCO class properties, then override the OnModelCreating() method. See an example below:
public class MyContext : DbContext
{
    . . .

    public DbSet<Stock> Stocks { get; set; }
    public DbSet<Invoice> Invoices { get; set; }

    . . .

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity().HasKey(p => p.StockId);
        modelBuilder.Entity().Property(p => p.ItemId).IsRequired();
        modelBuilder.Entity().Property(p => p.Quantity).IsRequired();

        modelBuilder.Entity().HasKey(p => p.InvoiceId);
        modelBuilder.Entity().Property(p => p.Name).HasMaxLength(50);
    }
}

If a database connection string has not been specified, EF will try to find an SQL Server Express for the database. If you would like EF to create the database in a specified server, then you need to specify a connection string and make sure to named it similar as the database context class' name.

Then we might want to specify Database.SetInitializer() method to determine the behaviour of EF Code First when initialising our database. By default, it will create the database if it not exists yet but will not change it afterwards even if the model(s) has changed. In an ASP.NET application, we put this inside Global.asax.cs file. An instance:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
There are three built in database initialisers options available:
- CreateDatabaseIfNotExists (default)
- DropCreateDatabaseIfModelChanges
- DropCreateDatabaseAlways
We can also pass null as the parameter to the Database.SetInitializer() method to skip database initialisation process.

By default the database will be initialised when the context is used for the first time. For example, when the code is trying to retrieve items from an entity. To do the database initialisation explicitly without waiting for the context to be used, call:
db.Database.Initialize(false);
For example, you can put this code below in Global.asax.cs
// do the database initialisation explicitly without waiting for the context to be used 
using (var db = new MyContext())
{
    db.Database.Initialize(false);
}

Friday, 2 September 2011

Entity Framework Code First - a Model that has Multiple Members Referring to another Single Model

Says we want to create a ‘Match’ model that will have two ‘Teams’.

The first thing that we need to do is to add two properties on the ‘Match’ class. In this example, we name them ‘HostTeamId’ and ‘GuestTeamId’ (line 9 & 12).

Then we need to add two virtual members to the class which are ‘HostTeam’ and ‘GuestTeam’ (line 15 & 18). I like to specify the ‘ForeignKey’ attribute explicitly to make it more readable even tough it may work if I omit those (not sure, I haven’t tried on this multiple references case).
public class Match
    {
        public int MatchId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public int HostTeamId { get; set; }

        [Required]
        public int GuestTeamId { get; set; }

        [ForeignKey("HostTeamId")]
        public virtual Team HostTeam { get; set; }

        [ForeignKey("GuestTeamId")]
        public virtual Team GuestTeam { get; set; }

    }

Then we also need to add virtual properties on the ‘Team’ class to indicate relationship with the ‘Match’ class.
public class Team
    {
        public int TeamId { get; set; }

        [Required]
        public string Name { get; set; }

        public string City { get; set; }

        public DateTime Founded { get; set; }

        public virtual ICollection<Player> Players { get; set; }
        public virtual ICollection<Match> HomeMatches { get; set; }
        public virtual ICollection<Match> AwayMatches { get; set; }
    }

Finally we need to implement the override method ‘OnModelCreating’ on our data context class. We need to specify both two referring members of ‘Match’ class ('HostTeam' and 'GuestTeam') with correct relationship to 'Team' class. In this case I use 'WithMany' and 'HasForeignKey' methods.
. . .
        public DbSet<MvcScaffoldTest.Models.Team> Teams { get; set; }

        public DbSet<MvcScaffoldTest.Models.Match> Matches { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HostTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HostTeamId)
                    .WillCascadeOnDelete(false);

            modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
        }
        . . .