Pages

Monday, October 7, 2013

Entity Framework 6.0

With the announcement of Visual Studio 2013 release date of November 13, 2013, you can look forward to the latest version of Entity Framework and its new features.  For those familiar with Entity Framework, there are two main options you can use when developing an application; code first or model first.  The new features of Entity Framework 6 includes several enhancements for the code first and model workflows as well as enhancements specific for code first only.
In addition to the new features, Entity Framework is now open source and is available at EntityFramework.codeplex.com.  Not only is the source code available but the nightly builds, issues, feature specs, and design meeting notes are also available on the CodePlex site.  Contributions are being accepted and are held to the same standards and code reviews as the Entity Framework development team.
Below is a quick overview of the new features available in Entity Framework for Code First and Model First options:

  • Asynchronous query and save
  • Connection resiliency
  • Code-based configuration
  • Database command interception/logging New features specifically for Code First:
  • Custom conventions
  • Stored Procedure Mapping
  • Let’s take a further look into some of the new features.
    Custom Code First Conventions
    Custom Code First conventions allow for bulk configuration for multiple entities and properties and was built to avoid repetitive, error prone configurations.  Code First conventions should be used when patterns in your model do not match the EF Code First Conventions, such as primary key naming where EF expects the [Key] annotation, ‘ID’ as the property, or property name followed by ‘ID’.  Code First Conventions should also be used if you do not particularly care for the default conventions Entity Framework provides.
    For example, rather than using the [Key] annotation, I can use a custom convention to override the default primary key identifier EF is expecting.  To do so, I can override the OnModelCreating event and add a custom convention as shown below.
    image
    So now rather than using the [Key] annotation in the model classes, I can leave the annotation off and my custom convention will set my properties with name ‘Key’ as a primary key in the database.
    Before
    After
    image image

    That’s great, but what if you need to do something a little more involved, such as follow a particular column naming convention as dictated by your DBA?  Well, again, you can use a custom convention to set the column names using the naming convention as prescribed.  The example below uses the property name and type to set the column name using lowercase with underscores between the words.
    image
    Database Command Logging
    Database command logging allows you to log every command or query sent to the database.  This allows you see what is really going on behind the scenes with what Entity Framework is doing when it communicates with the database.  In previous versions of EF in order to see the commands being sent to the database you had to open SQL management studio and use SQL Profiler.  Now with database command logging you can easily see the commands Entity Framework is sending to the database through items such as the console window.  Database command logging is best used to get an understanding of how Entity Framework is translating LINQ queries into SQL and is also great in debugging queries and trouble shooting performance issues. 
    For example, you can send the commands Entity Framework sends to the console window by adding the highlighted line below:
    image
    When you run the window console application, you can see the commands sent to the database as seen below:
    image
    Mapping to Stored Procedures using Code First
    Code First stored procedure mapping allows you to map to insert, update, and delete stored procedures to the Entity Framework model and was introduced as a result of many organizations requiring the use of stored procedures on an enterprise level.  Stored procedure mapping should be used when mapping to an existing database that utilizes stored procedures, required by the enterprise, when the need to run additional save logic that is best performed by the database, and when EF cannot map to the database schema.
    To use the stored procedure mapping for an entity, configure the desired entity by setting the MapToStoredProcedures property as show below.
    image
    In order to generate the stored procedures for the entity, add a new migration using the package manager window and EF will create the stored procedures.  Once the procedures are generated, update the database using the Update-Database command in the package manager.
    image
    Now rather than using an insert statement, the stored procedure is called and you can see the parameter mapping as well as the time taken to execute the procedure.
    image
    Async Query and Save
    Asynchronous query and save is a task based pattern for querying and saving to the database.  When used appropriately, it can improve performance and scalability.  Aysch should be used to reduce the number of resources used by the server (free up blocked threads), improve the responsiveness of the client UI by not blocking the main thread, and to allow for parallelism where you may need to bring back a lot of data to an application.  However, please not that parallelism cannot be executed on the same context instance so there are some limitations.
    To use asyc, mark the desired method as ‘asych’ and use return type of Task.  This tells the compiler that at some point there will be an operation but no CPU time is required from current thread while the operation completes.  The example below shows the changes to the method as well as the calling method to allow for async.
    image
    When we run the application, we can see the method is executed asynchronously and the current thread was not blocked as the application proceeded to write out the current date/time before the query completed to print the blogs (note the addition of the output of the date/time in the image above).
    image
    Code-Based Configuration
    Code based configuration is a code centric alternative to the <entityFramework> section in the web/app.config.  This feature was introduced because it is often easier to configure code rather than modifying the configuration file.  Code-based configurations should be used when you want to change the configuration specifically for your local environment or when using an loC container to control configuration.  The simplest way to add code base configurations is to derive a class from the DbConfiguration class which allows you to see the types that are configurable and provides strongly typed configurations.  When adding a class derived from DbConfiguration in the same assembly as the DB context,  Entity Framework will auto wire up the derived class.  If you want to do something a little more complex you can use the Dependency Resolver, which gives you a more flexibility but is less strongly typed.
    As you can see, there are many new features available with Entity Framework 6.0 that will make our jobs as developers easier, more effective and fun.
    Enjoy!

    No comments:

    Post a Comment