【问题标题】:How to configure a foreign key on an owned EF entity's property?如何在拥有的 EF 实体的属性上配置外键?
【发布时间】:2019-10-02 10:37:02
【问题描述】:

EF Core 3.0

我的域中有以下(简化的)实体:

class ApplicationUser {
    public int Id { get; set; }
    public string UserName { get; set; }
    // other properties
}

[Owned]
class Stamp {
    public string Username { get; set; }
    public ApplicationUser User { get; set; }
    DateTime DateTime { get; set; }
}

class Activity {
    public Stamp Created { get; set; }
    public Stamp Modified { get; set; }
    // other properties
}

它不是特别相关,但值得一提的是ApplicationUser.UserName 是一个非主键,唯一键。 (ApplicationUser 实际上继承自 ASP.NET IdentityUser。)

我想强制 Stamp.Username 是引用 ApplicationUser.UserName 的外键。

如果 Stamp 是一个常规的、非所有实体,那么就会建立这种关系:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // Stamp.Username => ApplicationUser.UserName
    modelBuilder.Entity<Stamp>(e => {
        e.HasOne(s => s.User)
        .WithOne()
        .HasForeignKey<Stamp>(s => s.Username)
        .HasPrincipalKey<ApplicationUser>(u => u.UserName);
    });
    ...
}

当我尝试创建迁移 (dotnet ef migrations add) 时,我收到 InvalidOperationException 说“无法将类型 'Stamp' 配置为非拥有,因为已经存在同名的拥有实体类型”。

如何使用 Fluent API 或其他方式实现我想要做的事情?

【问题讨论】:

  • 也许 this 或 this 文章可以帮助你。 This 可能是一种解决方案。
  • 谢谢,我已经能够使用第三个链接的答案作为一种可能的解决方案的基础。此评论不是描述该解决方案最合适的地方,因此我将添加一个答案。

标签: ef-code-first entity-framework-core


【解决方案1】:

你应该使用OwnsOne在所有者中配置它:

modelBuilder.Entity<ApplicationUser>().OwnsOne(user => user.Stamp, stamp => 
{
    // configure your stamp 
});

【讨论】:

    【解决方案2】:

    这是一种可能的解决方案,可能不是最优雅的解决方案。它基于ChW在cmets中提到的this answer。

    modelBuilder.Entity<Activity>(e => {
        e.OwnsOne(a => a.Created)
        .HasOne<ApplicationUser>()
        .WithOne()
        .HasForeignKey<Stamp>(s => s.Username)
        .HasPrincipalKey<ApplicationUser>(u => u.UserName);
    });
    

    这会在特定所有者实体 (Activity) 的特定 Stamp 出现 (Created) 上设置所需的外键。

    显然,对于每个其他 Stamp 出现(在此示例中为 Modified)和每个其他所有者实体(Activity 可能不是唯一的),都需要重复类似的代码块。

    顺便说一句,我最终还删除了 Stamp.User 导航属性,因为 EF 一直在使用它来自动创建另一个(不希望地)指向 ApplicationUser.Id 属性的外键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2015-06-03
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多