在 Entity Framework Core 3.1 中使用投影时不会跟踪更改

Ref*_*eft 5 c# entity-framework-core .net-core entity-framework-core-3.1

有预测(0 变化):

var changesBefore = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //before change - 0

var orderLocation = Db.OrderLocation.AsTracking().Select(ol => new OrderLocationEntity
{
    Id = ol.Id,
    Address = ol.Address,
    City = ol.City,
    Created = ol.Created,
    OrderId = ol.OrderId,
    Zip = ol.Zip
}).First();

orderLocation.Address = "address";

var changesAfter = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //after change - 0
Run Code Online (Sandbox Code Playgroud)

没有预测(1 处更改)

var changesBefore = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //before change - 0

var orderLocation = Db.OrderLocation.AsTracking().First();

orderLocation.Address = "address";

var changesAfter = Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //after change - 1
Run Code Online (Sandbox Code Playgroud)

设置

微软.EntityFrameworkCore 3.1.1

Microsoft.EntityFrameworkCore.Sqlite 3.1.1

var options = new DbContextOptionsBuilder<OrderDatabaseContext>()
                .UseSqlite("DataSource=:memory:")
                .Options;
Run Code Online (Sandbox Code Playgroud)

如果结果集包含来自 LINQ 组合的实体类型,EF Core 将跟踪它们。

来源

https://learn.microsoft.com/en-us/ef/core/querying/tracking

为什么使用投影时未跟踪更改?

Fab*_*bio 6

注意“实体类型”:

如果结果集包含来自 LINQ 组合的实体类型,EF Core 将跟踪它们。

来自相同的文档:

如果结果集不包含任何实体类型,则不会进行任何跟踪。

您的投影不包含实体类型,因此不会跟踪更改。

例如,如果您将引入属性来保留OrderLocationEntity实例,则该实例将由上下文跟踪

var location = Db.OrderLocation.AsTracking()
    .Select(ol => new OrderLocationEntity
    {
        Id = ol.Id,
        Address = ol.Address,
        City = ol.City,
        Created = ol.Created,
        OrderId = ol.OrderId,
        Zip = ol.Zip,
        Location = ol // entity instance passed to the projected object
    })
    .First();

location.Location.Address = "New Address"; 

Db.ChangeTracker.Entries<OrderLocationEntity>().ToList(); //after change - 1
Run Code Online (Sandbox Code Playgroud)

  • 因为 `new OrderLocationEntity` 是一个新实例,而不是由实际的“查询”创建的 (3认同)