Entity Framework CTP 4.0 – Code First Approach

Posted: October 3, 2010 in .NET, ADO.NET Entity Framework, C#
Tags: , ,

It has been a month or two  that Entity Framework CTP 4.0 bits have released.I had read through the feature list back then but could not manage time to take a detailed look until this weekend.I always felt that Entity Framework’s approach towards handling of configuration(object relational mappings) and plain .NET objects was bit restrictive and cumbersome respectively.The mappings are needed to be stored in Entity Data Model(.edmx) files which are nothing but xml files with object to relational store mapping information.There was no proper way to express this mapping through code or attributes.But with code first approach we will able to describe our model using plain .NET objects and map it to the database objects through .NET code.In this post we will discuss the very basic steps involved in doing so.

In this example we will use the following database table.

person

The C# class shown below will be mapped to this table.

public class Employee
    {
        public int EmployeeID {get;set;}
        public string FirstName { get; set; }
        public string LastName  {get;set;}
        public DateTime HireDate {get;set;}
        public DateTime EnrollmentDate {get;set;}
    } 

The next step will be to map this class to the Person table.To achieve this we need to use the EntityConfiguration<T> class in System.Data.Entity.ModelConfiguration namespace as shown below:

public class EmployeeConfiguration :EntityConfiguration<Employee>
    {
        public EmployeeConfiguration()
        {
            MapSingleType(e =>
                            new
                            {
                                PersonId = e.EmployeeID,
                                e.FirstName,
                                e.LastName,
                                e.HireDate,
                                e.EnrollmentDate
                            }
                          ).ToTable("dbo.Person");
            HasKey(e=>e.EmployeeID);
            Property(e => e.EmployeeID).IsIdentity();
            Property(e => e.FirstName).IsRequired();
            Property(e => e.LastName).IsRequired();
        }
    } 

The following things needs to be noted:

  • EntityConfiguration class exposes a method MapSingleType to map a C# class and create an EntityMap object.The method signature is
    • public System.Data.Entity.ModelConfiguration.EntityMap MapSingleType(System.Linq.Expressions.Expression<Func<TEntity,object>> propertyMap)

         Here we have mapped an anoynmous class created out of the Employee class where all the property names are  same as that of Employee class only EmployeeId property is transformed to PersonId.This is done because the column name is Person table is PersonId and column name of the database table and property name of the mapped type should match.

  • The HasKey method is used to mention which property will be used as the Primary Key.Here it is the EmployeeId property.The detailed signature is
    • public System.Data.Entity.ModelConfiguration.EntityConfiguration<TEntity> HasKey<TKey>(System.Linq.Expressions.Expression<Func<TEntity,TKey>> getKey)
  • The Property method and it’s several overloads belongs to StructuralTypeConfiguration<T> class from which EntityConfiguration inherits.The Property method and it’s overload returns instances of several types of property classes like PrimitivePropertyConfiguration,StringPropertyConfiguation and so on.These XXXPropertyConfiguration classes are used to specify whether a property is mandatory(IsRequired()), it’s maximum length(MaxLength) etc.

Now we have to create a context class which will talk to the database and help us to manipulate the data for a data model. We have inherited from the Sytem.Data.Entity.DbContext class to create our own context class.The DbSet<T> provides a collection of entity objects which we can manipulate within this context.

public class SchoolDBContext:DbContext
    {
        public SchoolDBContext(DbModel model,string name) : base(name,model ) { }
        public DbSet<Employee> Employees { get; set; }
    } 

Now we have to create the data model and attach it to the context.To do so we have to use the System.Data.Entity.ModelConfiguration.ModelBuilder class.We have instantiated the context using the data model and name of the database.If name is not specified then framework will assume this to be same as fully qualified type name of the context class i.e. EFCodeFirstDemo.SchoolDBContext in this case.

ModelBuilder builder = new ModelBuilder();
builder.Configurations.Add(new EmployeeConfiguration()); 

DbModel model = builder.CreateModel();
using (var context = new SchoolDBContext(model,"school"))
{
} 

So far we have not specified any connection string to connect to a server.This can be done by using DefaultConnectionFactory in the System.Data.Entity.Infrastructure.Database class as shown below:

Database.SetInitializer<SchoolDBContext>(null); 

Database.DefaultConnectionFactory = new
    SqlConnectionFactory("Server=SANKARSAN;Database=School;Trusted_Connection=True;"); 

The Database class exposes set of static properties which governs the AppDomain wide settings related to database.

Now we can use the following code to insert data into person table.

Database.SetInitializer<SchoolDBContext>(null); 

  Database.DefaultConnectionFactory = new
      SqlConnectionFactory("Server=SANKARSAN;Database=School;Trusted_Connection=True;");
  ModelBuilder builder = new ModelBuilder();
  builder.Configurations.Add(new EmployeeConfiguration()); 

  DbModel model = builder.CreateModel();
  using (var context = new SchoolDBContext(model,"school"))
  {
      Employee e = new Employee { 
          FirstName = "Sankarsan", 
          LastName = "Bose" ,
          HireDate = DateTime.Now,
          EnrollmentDate=DateTime.Now};
      context.Employees.Add(e);
      context.SaveChanges();
      Console.Read();
  } 

 

This post covered the very basic steps.In the posts to come we will explore each of these steps and related APIs in greater detail.

About these ads
Comments
  1. Entity Framework CTP 4.0 – Code First Approach « Sankarsan’s Journal…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. […] here to read the rest: Entity Framework CTP 4.0 – Code First Approach « Sankarsan's Journal No […]

  3. Wubbsy says:

    Why are.you doing it all the hard way? There are situations where it is useful to create a DbModel explicitly, but you’re not hitting any of those situations. Why not let the DbContext do all the hard work for you using conventions and then just override the conventions when you have to?

    • sankarsan says:

      It’s not question of the situation or it’s complexity :-)
      I just wanted to mention the possible steps involved in the code first model…additions/omissions based on scenarios are to follow…

  4. […] 14, 2010 by sankarsan In the last post we discussed about the basic steps involved in working with the new Entity Framework CTP 4.0 Code […]

  5. […] 17, 2010 by sankarsan In the last two posts I have discussed about Entity Framework CTP 4.0 Code First Approach and Database Initialization.Now we will take a look at how to define relationships and navigational […]

  6. agog says:

    Very useful sample and straightforward learning curve. thanks!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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