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.

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)

class exposes a method to map a C# class and create an EntityMap object.The method signature is

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)

method is used to mention which property will be used as the Primary Key.Here it is the EmployeeId property.The detailed signature is 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.