Home  >  Article  >  Backend Development  >  EF Core 2.0 new features

EF Core 2.0 new features

大家讲道理
大家讲道理Original
2017-05-31 14:39:042119browse




##Preface

The latest version of EF Core is currently

2.0.0-priview1-final, so this article is mainly about some instructions for this version.

Note: If you want to use .NET Core 2.0 in Visual Studio, you need at least Visual Studio 2017 15.3 preview version.

Recommended mysql video tutorials: "

mysql tutorial"

Install or upgrade to EF Core 2.0

You can use the following command to Install or upgrade your current version of .NET Core.

// 安装
PM> install-package Microsoft.EntityFrameworkCore.SqlServer -Pre -Version 2.0.0-preview1-final

// 升级
PM> update-package Microsoft.EntityFrameworkCore.SqlServer -Pre -Version 2.0.0-preview1-final

Toolkit

// 直接修改 CSPROJ 文件
<ItemGroup>
   <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" 
       Version="2.0.0-preview1-final" />
</ItemGroup>

// 或者通过以下命令
PM> update-package Microsoft.EntityFrameworkCore.Tools -Pre -Version 2.0.0-preview1-final

EF Core 2.0 New Features

Improved LINQ Translation

  • Avoid creating unnecessary subqueries

  • Some commands will switch to the client for execution

  • Only a few requests will retrieve all columns of the table

  • Sometimes without appropriate filter conditions, a single LINQ query is converted into N+1 queries.

EF.Functions.Like()

The EF.Functions properties were added in EF Core 2.0, and the EF Core Provider can use them to customize some functions mapped to the database methods of the latter operators so that they can be called in LINQ queries. For example:

var aCustomers =
    from c in context.Customers
    where EF.Functions.Like(c.Name, "a%");
    select c;

Separate entities and tables

What does it mean to separate entities and tables? In the past, a database table would be mapped to an entity object in EF, that is, there was a one-to-one correspondence between the table and the entity. Then in version 2.0, it is allowed to map some related entities to a table, and EF will maintain these instances or reference relationships.

modelBuilder.Entity<Customer>()
    .OwnsOne(c => c.WorkAddress);public class Customer
{    public int CustomerId { get; set; }    public Address WorkAddress { get; set; }
}public class Address
{    public string Line { get; set; }    public string PostalOrZipCode { get; set; }    public string StateOrProvince { get; set; }    public string CityOrTown { get; internal set; }
}

When generating a database table,

Customer and Address will be generated as one table.

Note: This function in priview1 is not complete yet.

Global query filtering

The new version introduces a function called "vertical filtering", which is a relatively common requirement.

When we define the EF Core context model, we can add some filtering conditions when creating the model, such as always filtering out some "logically deleted" data when querying.

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public int TenantId {get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasQueryFilter(p => !p.IsDeleted &&
                  p.TenantId == this.TenantId );
    }
}

This filter condition will be automatically applied when querying type data through direct query or navigation properties (

Include()). Of course you can use IgnoreQueryFilters() to disable this global filter in the query.

DbContext Connection Pool

Usually using EF Core in ASP.NET Core will involve a customized DbContext, which is then injected into the system container and then retrieved from the container through the constructor of the Controller. Get this object instance. This also means that a new instance will be created

on every request. In EF Core 2.0, a new way of injecting a custom DbContext is introduced, which explicitly uses an instance pool to inject it into the container.

services.AddDbContextPool<BloggingContext>(
    options => options.UseSqlServer(connectionString));

Using this method, when the Controller requests a DbContext instance, it will first check whether there is an available instance in the pool. Once the request is processed, any state attached to the instance will be reset. , and then the instance is returned to the pool.

This concept is somewhat similar to the database connection pool in ADO.NET, which has the advantage of saving the cost of initializing a DbContext instance. Many ASP.NET Core applications can use this approach to gain performance improvements.

Manually compiled queries

In previous versions of EF and Linq to SQL, there was an API for manually or explicitly compiling queries, which allowed applications to cache translated queries so that they Can be compiled once and executed multiple times.

Although EF Core can automatically compile and cache queries based on query expressions, this mechanism can obtain a small query performance improvement by bypassing hash calculations or caching, allowing applications to use delegates that have already been called. Query passed by chain compilation.

private static Func<CustomerContext, int, Customer> _customerById =
    EF.CompileQuery((CustomerContext db, int id) =>
        db.Customers
            .Include(c => c.Address)
            .Single(c => c.Id == id));

...using (var db = new CustomerContext())
{   var customer = _customerById(db, 147);
}

Others

EF Core 2.0 will also make some major adjustments to some logging and diagnostic infrastructure, as well as integration with Azure Application Insights.

The addition of Lazy Loading (lazy loading) function is still under discussion, and this function may be added in EF Core 2.1.




The above is the detailed content of EF Core 2.0 new features. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn