EF Core 11 breaking changes: assigning the same owned instance to more than one navigation now throws

未关闭 适合新手
#5,521 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
1/5
预计耗时
1-3 小时
新手友好度
74/100
Issue 类型
文档
描述清晰度
描述清楚
活跃度
活跃
技术栈
csharp
领域
documentation

调研方向

找到 EF Core 11 的重大变更页面,并阅读现有条目的格式。添加一个低影响条目,描述 Issue 中提到的行为变更和缓解方法,然后检查页面的链接和格式。条目清楚说明运行时异常,并建议使用独立实例或复杂类型,即为完成。

由索引模型根据 Issue 内容生成。

描述

Issue or suggestion

dotnet/efcore#38446 (11.0 preview 6) made EF throw when the same owned instance is referenced from more than one ownership navigation. The change isn't listed on the 11.0 breaking changes page, and it caught us during the upgrade because one of these patterns saved fine on 10.0:

var customer = db.Customers.Single(c => c.Id == 1);
customer.Billing = customer.Shipping;
db.SaveChanges();

10.0.15 saves it: both column sets get the Shipping values. 11.0.0 throws:

InvalidOperationException: The same object instance of type 'Address' is being referenced from the navigation 'Shipping' on 'Customer' and from the navigation 'Billing' on 'Customer'. Owned entity types cannot have multiple owners pointing to the same instance. Consider creating a copy of the object to use for each navigation.

The PR description says the old behavior was a confusing FK error at SaveChanges. That's what happens in some cases, but not in this one. There's also a second case that didn't throw on 10.0: when two new owners share an optional owned instance, 10.0 saves both, and the first owner silently ends up with null for that navigation (repro below). So the new check is a good change. It's just that code that ran on 10 now fails at runtime after the upgrade, and nothing at build time points to it.

Could this get a low impact entry on the breaking changes page? Roughly:

  • Old behavior: sharing an owned instance either failed at SaveChanges with an unrelated error, or saved. When it saved, two navigations of a tracked owner both got the same values, or one of two new owners lost the value.
  • New behavior: InvalidOperationException when the entity is tracked or on DetectChanges.
  • Mitigation: give each navigation its own instance (copy it), or map the type as a complex type, which has value semantics.

I can open a PR for it if that helps.

Repro (SQLite):

#:package [email protected]
#:property PublishAot=false

using Microsoft.EntityFrameworkCore;

using (var db = new AppDb())
{
    db.Database.EnsureDeleted();
    db.Database.EnsureCreated();
    db.Add(new Customer { Id = 1, Shipping = new Address { City = "Paris" }, Billing = new Address { City = "Lyon" } });
    db.SaveChanges();
}

Run("Existing customer: Billing = Shipping", db =>
{
    var customer = db.Customers.Single(c => c.Id == 1);
    customer.Billing = customer.Shipping;
    db.SaveChanges();
});

Run("Two new customers share one optional Billing instance", db =>
{
    var billing = new Address { City = "Berlin" };
    db.Add(new Customer { Id = 2, Shipping = new Address { City = "Rome" }, Billing = billing });
    db.Add(new Customer { Id = 3, Shipping = new Address { City = "Oslo" }, Billing = billing });
    db.SaveChanges();
});

using (var db = new AppDb())
{
    foreach (var c in db.Customers.AsNoTracking().OrderBy(c => c.Id))
    {
        Console.WriteLine($"Customer {c.Id}: Shipping={c.Shipping.City}, Billing={c.Billing?.City ?? "<null>"}");
    }
}

static void Run(string name, Action<AppDb> action)
{
    Console.WriteLine(name);
    try
    {
        using var db = new AppDb();
        action(db);
        Console.WriteLine("  saved");
    }
    catch (Exception e)
    {
        Console.WriteLine($"  {e.GetType().Name}: {e.Message}");
    }
}

public class Customer
{
    public int Id { get; set; }
    public Address Shipping { get; set; } = null!;
    public Address? Billing { get; set; }
}

public class Address
{
    public string City { get; set; } = "";
}

public class AppDb : DbContext
{
    public DbSet<Customer> Customers => Set<Customer>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=repro.db");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>(b =>
        {
            b.Property(c => c.Id).ValueGeneratedNever();
            b.OwnsOne(c => c.Shipping);
            b.OwnsOne(c => c.Billing);
        });
    }
}

Output with 11.0.0:

Existing customer: Billing = Shipping
  InvalidOperationException: The same object instance of type 'Address' is being referenced from the navigation 'Shipping' on 'Customer' and from the navigation 'Billing' on 'Customer'. Owned entity types cannot have multiple owners pointing to the same instance. Consider creating a copy of the object to use for each navigation.
Two new customers share one optional Billing instance
  InvalidOperationException: The same object instance of type 'Address' is being referenced from the navigation 'Billing' on 'Customer' and from the navigation 'Billing' on 'Customer'. Owned entity types cannot have multiple owners pointing to the same instance. Consider creating a copy of the object to use for each navigation.
Customer 1: Shipping=Paris, Billing=Lyon

Output with 10.0.15:

Existing customer: Billing = Shipping
  saved
Two new customers share one optional Billing instance
  saved
Customer 1: Shipping=Paris, Billing=Paris
Customer 2: Shipping=Rome, Billing=<null>
Customer 3: Shipping=Oslo, Billing=Berlin
主要语言
Mermaid
星标
1.7k
派生
2k
平均合并
1 天 3 小时
30 天内合并 PR
33

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

dotnet/EntityFramework.Docs 的其他 Issue

查看 dotnet/EntityFramework.Docs 的全部 Issue

相似的 Issue

更多 Documentation Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。