Skip to main content
What's new in Entity Framework Core 1.0

Quick summary of what’s new in Entity Framework Core 1.0

Entity Framework Core 1.0 has been already out and Microsoft has already started working on Entity Framework Core 1.1. One of the advantage of ASP.NET Core is cross-platform support similarly Entity Framework Core (EF Core) is also cross-platform version of Entity Framework. So here is a quick and short summary of what’s new in Entity Framework Core compared to its previous versions.

What’s new in Entity Framework Core

  • The first and most important change is that “Entity Framework Core, like ASP.NET Core, is cross platform.”
  • EF Core is lightweight and extensible compared to its previous versions. EF Core was developed from scratch and it is decomposed in smaller packages so you can use only those which are needed in your project. And you can also extend those packages.
  • EF Core can connect to different database providers. At the time of writing this post, EF Core supports following db providers.

    MySQL and Oracle support is also coming soon.

  • EF Core support InMemory Provider. It’s a new DB Provider which holds everything in memory. There is no database written to disk. This is useful for unit testing entity framework DB operations as InMemory storage behaves same as the actual database storage. Read How to use Entity Framework Core InMemory provider with ASP.NET Core.
  • EF core also support non-relational databases like Azure table storage and NoSQL.
  • No EDMX. EF Core uses either code first or Database First approach. Future releases of EF Core may support EDMX.
  • Database initializers no longer exist in EF Core. There are no such strategies as CreateDatabaseIfNotExists, DropCreateDatabaseAlways, DropCreateDatabaseIfModelChanges, MigrateDatabaseToLatestVersion. Following 2 methods EnsureCreated() and EnsureDeleted() are introduced to create/delete the database. To implement DropCreateDatabaseAlways, you need to do the following,
    context.Database.EnsureDeleted();
    context.Database.EnsureCreated();
    
  • EF Core is for only those applications that target .NET Core, such as Universal Windows Platform (UWP) and ASP.NET Core applications. These applications cannot use EF6.x as it requires the Full .NET Framework (i.e. .NET Framework 4.5).
  • DbContext.Database.Log is used in prior version to log queries. But it is no longer available in EF Core. You can use .NET Core inbuilt logging feature to log EF queries.
  • EF Core supports batching of statements. It doesn’t send individual command for every insert/update/delete statement. It will batch multiple statements in a single round trip to the database. As an example, you want to update salary of 10 employees in a table. With EF 6, there would be 1+N round-trips to the database. One to load the data and then one for each row. But with EF core, save operations are batched so that there would be only two round-trips to the database.
  • EF Core no longer supports Stored procedure mapping. But technically you can still use them via raw SQL. Read How to execute Stored Procedure in Entity Framework Core.
  • EF Core now supports Sequence and HiLo algorithm for primary key value generation. Read my post Use SQL Server Sequence in Entity Framework Core to Create Primary Key. And HiLo is a pattern where the primary key is made of 2 parts “Hi” and “Lo”. Where the “Hi” part comes from database and “Lo” part is generated in memory to create unique value. Remember, “Lo” is a range number like 0-100. So when “Lo” range is exhausted for “Hi” number, then again a database call is made to get next “Hi number”. HiLo is supported via sequence.This exists in NHibernate since ages. Read Use HiLo to generate keys with Entity Framework Core
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Unicon>(b =>
        {
            b.HasKey(e => e.Identifier);
            if (_useSequence)
            {
                b.Property(e => e.Identifier).ForSqlServerUseSequenceHiLo();
            }
            else
            {
                b.Property(e => e.Identifier).UseSqlServerIdentityColumn();
            }
        });
    }
    
  • In EF Core, Composite key can only be configured via Fluent API. With EF 6.x, you define composite key via following way.
    public class Employee
    {
        public Employee()
        { 
            
        }
        [Key]
        [Column(Order=1)]
        public int EmployeeKey1 { get; set; }
         
        [Key]
        [Column(Order=2)]
        public int EmployeeKey2 { get; set; }
         
        public string EmployeeName { get; set; }
            
    }
    

    But this will not work with EF Core. This can be done in EF Core via Fluent API.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
             .HasKey(c => new { c.EmployeeKey1, c.EmployeeKey2});
    }
    
  • With EF Core, alternate or unique key can be set directly along with Primary key. You can set unique key either via Fluent API or Convention. Using fluent API, use HasAlternateKey method and use HasPrincipalKey method while using Convention. At this moment, unique key can’t be set via Data Annotations. Alternate key will be named as AK_<type name>_<property name>. Following is sample code to set using fluent API.
    protected override void OnModelCreating(ModelBuilder modelBuilder)  
    {  
       modelBuilder.Entity <Student> ()  
          .HasAlternateKey(e => e.StudentCode);  
    }  
    
  • Complex/Value type is not supported in EF Core.
  • EF Core supports shadow properties. Shadow properties are properties that do not exist in your entity class. The value and state of these properties is maintained purely in the Change Tracker. Shadow property can be created via following way
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       modelBuilder.Entity<blog>()
          .Property<DateTimeOffset>("LastModified");
    }
    

    And you can set value in following way,

    context.Entry(myblog)
            .Property("LastModified").CurrentValue = DateTimeOffset.Now;
    

    You can refer them in linq queries via the EF.Property static method.

    var blogs = context.Blogs
        .OrderBy(b => EF.Property<DateTime>(b, "LastModified"));
    

    Read How to use Shadow Properties with Entity Framework Core

  • EF Core has no inbuilt support for seed data. However, there are ways to seed the data. You can find the solution here and here.
  • At the time of writing this post, EF core only supports eager loading. It doesn’t support lazy loading and explicit loading. There is no update on support of lazy loading, however explicit loading will be supported in the EF Core 1.1 release as mentioned here. Read this post to understand these loading techniques.
  • EF core supports Mixed client/server evaluation. Mixed client/server evaluation enables queries to contain logic that cannot be evaluated in the database, and must therefore be evaluated after the data is retrieved into memory. In following code, there is a helper method AddTitle which adds “Mr” title to first name and returns the updated string.
    public static string AddTitle(string sFirstName)
    {
        if (!sFirstName.ToLower().StartsWith("mr"))
        {
            sFirstName = string.Concat("Mr.", sFirstName);
        }
        return sFirstName;
    }
    

    Below is EF Code. Here SQL has no insight about this method implementation therefore it can’t translate this in SQL.

    var emp = context.Employee 
        .Where(emp => emp.Gender == "M")
        .Select(employee => new
        {
            FirstName = AddTitle(employee.FirstName),
            LastName  = employee.LastName
        })
        .ToList();
    

    In this case, the rest of the query is executed and once the data is returned to the client, this method gets called on the client side. This feature should be used carefully as it can lead to performance issue. Just think, if the helper method is part of where statement. In that case, all the data is fetched into memory and then the helper method is applied on the client side. So be careful while using this feature.

  • Connection resiliency is not supported at this point of time. However EF Core 1.1 release should support this.
    [Connection resiliency refers to the ability for EF to automatically retry any commands that fail due to these connection breaks.]
  • EF Core supports mixing FromSQL with LINQ expressions. You can add a Where or OrderBy call to a table-valued function query.
    context.FromSql<Employee>("SELECT * FROM Employee")
                    .OrderBy(e => e.EmpName);
    
  • Migration is supported in EF Core but automatic migration is removed.
  • ObjectContext API and Entity-SQL are removed.

Summary

Entity Framework Core 1.0 RTM is out, but if you compare with EF6.x, you will notice that many important features are missing. And probably that’s why it’s not advisable to migrate to EF Core. Keeping my fingers crossed for better shape and more mature EF Core in near future releases. I hope you liked it.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

2 thoughts to “Quick summary of what’s new in Entity Framework Core 1.0”

Leave a Reply

Your email address will not be published. Required fields are marked *