How to create a Code-First EF model

EF 4.1 introduces two new features

  • The DbContext API is a simplified abstraction over ObjectContext and a number of other types
  • Code First is a new development pattern that provides an alternative to the Database First and Model First patterns

Code First is focused around defining your model using .NET classes. These classes can then be mapped to an existing database or be used to generate a database schema. Additional configuration can be supplied using Data Annotations or via a fluent API.

Create the entities for the model by defining POCO (“plain old CLR object”). Classes Relationships should be virtual to support lazy-loading. A property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by “ID” If the type of the primary key property is numeric or GUID it will be configured as an identity column

public class Category { 

     public int CategoryID { get; set; } 
     public string CategoryName { get; set; } 
     public virtual ICollection Products { get; set; } 

public class Product { 
     public int ProductID { get; set; } 
     public string ProductName { get; set; } 
     public string CategoryID { get; set; } 
     public virtual Category Category { get; set; }

Define a context that derives from System.Data.Entity.DbContext and exposes a typed DbSet for each class in my model. You will need to add a reference to the
EntityFramework.dll assembly and import System.Data.Entity namespace

public class NorthwindContext : DbContext
 public DbSet Categories { get; set; }
 public DbSet Products { get; set; }

The easiest way to point Code First to an existing database is to add a .config connection string with the same name as your derived DbContext

< / connectionStrings>

Use the DbContext
If you do not specify a connection string for an existing database then DbContext by convention creates a database for you on localhost\SQLEXPRESS
• The database will be named after the fully qualified name of your derived context

using (var db = new NorthwindContext())
 var food = new Category { CategoryName = "Foods" };
 int recordsAffected = db.SaveChanges();

You can apply annotations to your model, like
• Key, StringLength, MaxLength, ConcurrencyCheck, Required,
Timestamp, ComplexType, Column, Table, InverseProperty,
ForeignKey, DatabaseGenerated, NotMapped

public class Category
 public int CategoryID { get; set; }
 [MaxLength(20, ErrorMessage="20 chars max!")]
 public string CategoryName { get; set; }

Considered a more advanced feature and we would recommend using Data Annotations unless your requirements require you to use the fluent API
Configuring/Mapping Properties and Types with the Fluent API

public class NorthwindContext : DbContext
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 modelBuilder.Entity().Property(s => s.Name).IsRequired();

Custom primary key convention
Any property in our model named Key will be configured as the primary key of whatever entity its part of

public class ProductContext : DbContext
 static ProductContext()
 new DropCreateDatabaseIfModelChanges());
 public DbSet Products { get; set; }
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 .Where(p => p.Name == "Key")
 .Configure(p => p.IsKey());

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s