Exploring Entity Framework Code First

When Entity Framework 3.5 was shipped in 2008, it restricted development to the ugly xml based mapping embedded in the EDM files.
Fast forward to 2013 and you will see and experience a completely different framework; flexible, configurable and easy to use.
Developers can now apply Domain Driven Design and other design patterns (by working with the customer to understand the problem they are trying to solve, NOTHING MORE) to write their application instead of writing data centric application.

Entity Framework provides us with the tools to help us embrace design patterns and Test Driven Development(TDD). Using Entity Framework’s Code first allows us to create our domain model without worrying about the database, persistence or UI.
Let’s create a simple example. In this example, we will create product and category models where each product is associated with a category and each category can have zero to many products.
Here is the product class:

public  class Product
       public int Id { get; set; }
       public string Name { get; set; }
       public decimal Price { get; set; }
       public virtual Category Category { get; set; }

The only reason the Category property in our product class is marked virtual is to let Entity Framework use lazy loading when we query the database. The second class is our Category class:

public  class Category
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual IList<Product>  Products { get; set; }

The next step is to start using entity framework. To do that, we will need to install the framework bits into our console project (or whatever project type you choose). To install the framework, you need to access the NuGet Package Manager. In visual Studio go to Tools-> NuGet Package Manager-> Click on Package Manager Console.

In the Package Console Manager, type install-package entityframework and press enter. Once the installation is complete, create a class in your project and name it StoreContext (any meaningful name will do). StoreContext class must inherit from DbContext. Add the following properties to your class:

class StoreContext : DbContext
       public StoreContext()
           : base("SampleStoreDatabase")
       public DbSet Products { get; set; }
       public DbSet Categories { get; set; }

The next step is to build your project just to make sure you didn't miss anything. Now that we have a successful build, let’s perform the following steps to enable code first:

  1. Go to the Package Manager and type “Add-Migration InitialSetup” without the quotes. This will tell visual studio to enable code first and start creating your database
  2. Again, while you are in NuGet Package Manager, type “Update-Database” (without the quotes). Once the update-database command is complete, you should have a database in either SQL server or localdb server (Mine was in SQLEXPRESS).
  3. You can view the database by going to the server explorer and clicking on Data Connections and then by clicking on Add Connection
    Your server explorer should look like this screen capture:

Or this if you don't have SQLEXPRESS installed:

3. Finally, once the connection is added, visual studio server explorer will look like this:

Now that we can see and open our database, we will be using Entity framework code first to modify it, and then set up some default rows. If you open the database and view the Products table (Right click on the table and click on Open Table Definition), you will notice that the Data Types are off (The name is set to nvarchar(Max) and Price is set with decimal precision of (18,2).

The easiest place to modify these values is in our StoreContext class. We will have to override OnModelCreating method and add some additional configurations. Add the following code snippet to your class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
           modelBuilder.Properties<decimal>().Configure(p => p.HasPrecision(8, 2));
           modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(50));

Here, we used the modelBuilder to apply the new conventions as the comment indicated. To apply the changes to the database, we need to build the project then use Package Manager to add a new migration by executing Add-Migration ChangeDataTypes (ChangeDataType is just a name for the migration, it can be anything). After adding the migration (Visual Studio will add a new C# class in the Migration folder), you will need to perform an update-database command in the package manager to update the database. If you open your view the products Table definition again, you will see the changes have taken effect in the table. Now that we've changed our tables definitions using code first, let’s start adding some default products and categories to ensure we always have values to test against. Open the Migration folder in your project then open the Configuration.cs class and add the following code snippet in the seed method:

 //look for the name field of the product table when performing the upsert (update or insert) operation
          protected override void Seed(EFStore.Infrastructure.StoreContext context)
       //look for the name field of the product table when performing the upsert opeartion,
       //if there is a product with the name pepsi, ignore it and move on to the next one
       context.Products.AddOrUpdate(p => p.Name,
           new Product { Name = "Pepsi",
                         Category = new Category { Name = "Soft Drinks" },
                         Price = 1.00m
           }, new Product { Name = "heineken", Price = 8.00m,
               Category = new Category { Name = "Beer" } });

In here we are instructing entity framework to keep default records of two Products and two categories. We use the AddOrUpdate method using the Name property of the Product model to tell the framework to check on the name field. If we have a product with the name of Pepsi, entity framework will issue an update command, otherwise it will issue an insert command to add it to the database.

Build your project and test it by writing this snippet in your main method:

using (var dbcontext = new StoreContext())
    var products = from s in dbcontext.Products select s;
    foreach (var s in products)
        Console.WriteLine(s.Name + " " + s.Category.Name);

Your console should display the two records with their category name respectively.

Final thought

While I will be the first to admit that these additions are nothing less than impressive, I still think it lacks some important features found in matured ORMS like nHibernate (batch processing, future queries and caching...etc)

Comments (5) -

This is by far the best and the most detailed EF tutorial I have even seen. Thank you very much


my response 2/28/2014 5:34:14 PM

Utterly  written   written content ,  thankyou  for  selective information .

My research has been enhanced by you information, I'm thankful for the post

The information here is first class, I hop I can come back again when I have the time.

swarovski tree topper 6/4/2014 11:20:34 PM

Each color organized table is layered with ornate necklaces, dangly earrings, chunky rings and matching necklace.
Usually are carat maybe the stone's carat weight, color, clarity, and cut.http://www.1080i.co.uk

Comments are closed