DotNetCurry Logo

What’s New in Entity Framework 6.0 RC1

Posted by: Pravinkumar Dabade , on 9/13/2013, in Category Entity Framework
Views: 47402
Abstract: In this article, we will talk about some of the new features introduced in Entity Framework 6.0 RC1

Entity Framework 6, Microsoft’s primary data access platform in the .NET Framework, is the first open source release of Entity Framework being developed in CodePlex. In this article, we will explore some new features introduced in Entity Framework 6.0 RC1. We will mainly talk about –

  • Customizing Code First Conventions.
  • Logging of database commands.
  • Stored Procedure Mapping.
  • Asynchronous Queries and Save support.
  • Code based configuration support.
  • EF Power Tools (not new to EF6).

So, let’s get started with Visual Studio 2012 and create a new Console Application with the name EF6Demos.

 

Once the application is ready, add the following classes in your application.

public class Customer
{
    public int CustomerID { get; set; }
    public string ContactName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public List<Order> Orders { get; set; }
}


public class Employee
{
    [Key]
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public List<Order> Orders { get; set; }
}


public class Product
{
    [Key]
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public int AvailableQty { get; set; }
}


public class Order
{
    [Key]
    public int OrderID { get; set; }
    public DateTime OrderDate { get; set; }
    public DateTime RequiredDate { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public int CustomerID { get; set; }
    public int EmployeeID { get; set; }
}

Once you add these classes, now let’s add a Context class as shown below –

public class NorthwindContext:DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Order> Orders { get; set; }
}

Add the following code in your Main method –

static void Main(string[] args)
{
    RunCodeFirstMethod();
    Console.WriteLine("Done!!");
    Console.Read();
}

private static void RunCodeFirstMethod()
{
    NorthwindContext dataContext = new NorthwindContext();
    dataContext.Customers.Add(new Customer()
    {
        ContactName="John R.",
        Address="E-Street",
        City="London",
        State=null,
        Country="UK",
    });
    dataContext.SaveChanges();
    var query = from cust in dataContext.Customers
                select cust;
    foreach (var cust in query)
    {
        Console.WriteLine(cust.CustomerID + "----" + cust.ContactName);
    }
}

This is not anything new which we did above. Now if you check your localdb, you will find the database got created with all the tables as well as record(s) got inserted in our Customers Table as shown below –

sqlserverobexp

If you observe in the above diagram, we have all the tables created under database “EF6Demo.NorthwindContext”. The columns names are property names. Any property marked with the Key attribute has become a primary key. Also the string column has become nvarchar with the size max.

You will also find one extra table “_MigrationHistory” which contains the history about the database migration. Let’s say that you have made few changes to the Models and you want to update those changes into the database. Let’s see how to do the same. First open the “Package Manager Console” from Tools > Library Package Manager Menu.

Now type the below command in our Console as shown below

Enable-migrations

When you enable the migration, you will find a folder under solution explorer with the name “Migrations” which contains two classes. For our purpose, we will make use of Configuration class. The folder looks like below –

migrationfolder

Now open the InitialCreate.cs file. You will find the commands to create tables. Let’s make a small change in our Product model. Add a property called discontinued which is Boolean property to check whether the product is continued or discontinued.

public bool Discontinued { get; set; }

Let’s update the changes into our database. Type the following command in our Package Console Manager –

add-migration ProductsDiscontinued

Once the command gets completed successfully, a new class gets added into our migration folder with the name ProductDiscontinued. You can modify the default setting as per your requirements and update the same back to the database as shown below –

defaultvalue

Write the following command in our Package Console Manager –

update-database

Check the database and Products table. You will find the discontinued column as shown below –

modifiedproducttbl

Let’s now see the Configuration class. In EntityFramework 6,  we have something called the ContextKey. You can now have multiple code first model which can target the same database and you can use the context key to differentiate them.

Take a look at the table “_MigrationHistory” . The table should look like below –

migrationhostorytable1

You can now see our Products Discontinued column migration entry into _MigrationTable.

Customizing Code First Conventions

When you use Code First Model, there are lots of default conventions which you would like to override and avoid repetitive configurations. For example, let’s say, you want to rename a column, change the size of the column or want to decide the primary key column names etc.

Now you can achieve all these using EF 6 Custom Code First Conventions. Let’s see this in action. First of all remove all the key attributes from our models. By default Entity Framework expects the Primary Key column name as ID or the Model Name and ID. If you don’t follow this, you can use the Key attribute. After removing all the Key attributes, run your application and you may get an exception in case you have not followed any of the default rules. The exception looks like below –

pkexception

Try to change the size of the column. As you saw earlier, when the database got created first, all the string columns length was nvarchar(max). Let’s change the maxlength to 300. For this, we will override the method in our context class as shown below –

public class NorthwindContext:DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<string>().Configure(col => col.HasMaxLength(300));
        modelBuilder.Properties().Where(p => p.Name == "ProductName").Configure(p => p.HasColumnName("Name"));
    }
}

Run the following command in our Package Manager Console –

Add-migration updatecolumns

Update-database

So what are we doing in the OnModelCreating method? We are first of all changing all the string columns [NVARCHAR (MAX)] to 300 characters length. Then we are changing the ProductName column to Name column.

Check your database and you will see a similar output -

updatecolname

Logging of database commands

Now let’s take a look at another feature of EF 6.0 which is logging of database commands. The database command logging helps you to understand what’s going on when the data is pushed or pulled.

Let’s try logging our Code First Model commands as shown below –

dataContext.Database.Log = Console.Write;

I have written this code in our RunCodeFirstMethod after declaring the object of NorthwindContext.

Now observe the console output and you will see the Select and Insert statement as shown below –

logoutput

Stored Procedure Mapping

Let’s see another feature of EF 6.0 which is configuring/map stored procedures for Insert, Update and Delete. Let’s take an example of the same –

mapsp

Now write this command in our Package Manager Console –

add-migration ProductsSP

update-database

After running the above commands, you can see all the stored procedures generated in your database under Programmability as shown below –

sps

To map the stored procedures to all the models, you can write the following code –

mapallsps

Now write the following command in our Package Manager Console –

add-migration AllModelsSP

update-database

After running above commands, you will see all the stored procedures generated in your database under Programmability. For more information, please check the article – Entity Framework 6: DB Logging and Stored Procedure Mapping for EF Code First

Asynchronous Queries and Save support

Another feature of Entity Framework 6.0 is Async queries and saving data into database asynchronously. This adds support for the task-based asynchronous patterns that were introduced in .NET 4.5 and was not supported by EF 5.0.

Let’s take a look at an example. I am modifying the method RunCodeFirstMethod() in my Program class as shown below –

private static async Task RunCodeFirstMethod()
{
    NorthwindContext dataContext = new NorthwindContext();
    dataContext.Database.Log = Console.Write;
    dataContext.Customers.Add(new Customer()
    {
        ContactName="John R.",
        Address="E-Street",
        City="London",
        State=null,
        Country="UK",
    });
    await dataContext.SaveChangesAsync();
    var query =await (from cust in dataContext.Customers
                select cust).ToListAsync();
    foreach (var cust in query)
    {
        Console.WriteLine(cust.CustomerID + "----" + cust.ContactName);
    }
    dataContext.Database.Log = Console.Write;
}

In the above method, we are waiting till the time the changes are not saved into the database. We are also waiting till the time the LINQ query is not getting completed. Then we are returning a Task as an output of our method.

Also please make a note that the ToListAsync() method comes from System.Data.Entity namespace. So make sure you import this namespace. This is an extension method of LINQ.

Now let’s modify the Main method and display other messages on the console before the Asynchronous method gets executed. This will actually show you that the main thread is executing while the method “RunCodeFirstMethod” runs in a background without blocking the main thread.

You can see the output as shown below –

asyncoutput

Take a closer look at the output window which shows “@” sign first and result after.

Code based configuration support

Another new feature of Entity Framework 6.0 is Code Base Configuration support. Until now, you could apply EF configurations traditionally using various configuration files [XML] like App.Config/Web.Config. Now you can add configurations using code as well. Let’s see an example of the same.

When you want to use Code Based Configurations in EF 6.0, you will have to derive your own configuration class using DbConfiguration class which is available under System.Data.Entity namespace. So let’s add a class EF6DemoConfiguration and derive it from DbConfiguration class as shown below –

public class EF6DemoConfiguration:DbConfiguration
{
}

This class provides various configuration methods which you can use for configuring Entity Framework

Let’s first of all add a class with the name EF6CommandInterceptor and implement an interface IDbCommandInterceptor which is available under the namespace using System.Data.Entity.Infrastructure.Interception. Once you implement the interface, you will find couple of interesting methods which will get executed before or after the EF database command gets executed. Let’s write some code in few of these methods as shown below

public class EF6CommandInterceptor:IDbCommandInterceptor
{
public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
    using (StreamWriter SW=new StreamWriter(@"E:\EF6Log.txt",true))
    {
        SW.WriteLine(command.CommandText);
        SW.Close();
    }
}

public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}

public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
    using (StreamWriter SW = new StreamWriter(@"E:\EF6Log.txt", true))
    {
        SW.WriteLine(command.CommandText);
        SW.Close();
    }
}

public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
}

public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext< object > interceptionContext)
{
}

public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext< object > interceptionContext)
{
}

So if you observe, we have NonExecuteQuery, ExecuteReader and ExecuteScalar methods which are getting executed before and after the EF database commands (which we are now intercepting). Now add a constructor in our EFDemoConfiguration class and add the interceptor as shown below –

public class EF6DemoConfiguration:DbConfiguration
{
    public EF6DemoConfiguration()
    {
        this.AddInterceptor(new EF6CommandInterceptor());
    }
}

Write the following command in our Package Manager Console –

update-database

Check your EF6Log.txt file which will show you all the commands which got intercepted.

Entity Framework Power Tools

The Entity Framework Power Tools are not new to EF 6 but they are compatible with Visual Studio 2010 and 2012 ( till update 2) and Entity Framework 4.2 to 6.0 RC. the version available of this writing is Beta 3. To install these power tools, click on Tools Menu and click on Extensions and Updates. Search for “Entity Framework” and you will see the power tools as shown below –

efpowertools

Once you install the power tools, let’s get back to our EF6Demo Console Application and right click the NorthwindContext class. You will find a context menu Entity Framework and other options under the Entity Framework menu as shown below –

efpowertoolscontextmenu

As shown above, click on “View Entity Data Model (Read-only)” menu and it will show you the Entities in an Entity Designer with all relations as shown below –

efdesigner

Pretty cool!

In this article, we have explored some new features which are introduced in Entity Framework 6.0 RC1. With all these new features and more to come, Entity Framework has enabled .NET developers to work with relational data using domain-specific objects, with ease.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Allen on Friday, September 13, 2013 9:04 AM
Great article thanks! That feature of seeing the Entity Data Model diagram with the power tools is awesome. Has that always been around for Code First approach + power tools, or brand new to EF6 and the Power Tools?
Comment posted by Suprotim Agarwal on Friday, September 13, 2013 9:40 AM
The Entity Framework Power Tools are not new to EF 6 but it's worth mentioning that they are compatible with Visual Studio 2010 and 2012 and Entity Framework 4.2 to 6.0 RC. This point has been added to the article. Sorry about the confusion
Comment posted by werwe on Saturday, September 14, 2013 2:00 AM
This is not new
Comment posted by hmc on Wednesday, November 13, 2013 11:00 AM
If you ever developed with sql server there nothing very awesome here
Comment posted by Brandon on Monday, January 6, 2014 9:30 AM
Can you make the sections have an id so I can book mark or link directly to specific sections?
Comment posted by Suprotim Agarwal on Tuesday, January 7, 2014 7:05 PM
@Brandon: You mean adding anchors?
Comment posted by mm on Friday, January 31, 2014 12:02 AM
Nice article thanks
Comment posted by Tony on Tuesday, February 4, 2014 11:51 PM
Wonderful walk-through of new features. Thank you.