【问题标题】:EF Core Join using Include but ForeignKey is not Primary Key on the other tableEF Core Join 使用 Include 但 ForeignKey 不是另一张表上的主键
【发布时间】:2019-02-21 04:30:38
【问题描述】:

我正在尝试将我的表与另一端的 ForeignKey 和 PrimaryKey 相关联。但现在我将使用一个 ForeignKey,它不是所述表的主键。我使用的是 [InverseProperty],但我认为它有一个错误,因为我已经环顾了好几个小时,而且他们都说了同样的话。

文档表:

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    [NotMapped]
    public virtual User Author { get; set; }
}

用户

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }

    [NotMapped]
    [ForeignKey("AuthorId")]
    public virtual Document Document { get; set; }
}

上下文:

modelBuilder.Entity<User>(entity =>
        {
            entity.HasOne(u => u.Document)
            .WithMany("AuthorId");
        });

我正在尝试使用他们here 的解决方案,但没有运气。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 一个用户会有多个文档,不是吗?请清楚。
  • 是的。一个用户可以有多个文档。我现在会尝试你的回答,我对此感觉很好。

标签: asp.net-core entity-framework-core ef-core-2.2


【解决方案1】:

但现在我将使用一个不是所述表的主键的 ForeignKey。

为此,您可以使用 EF Core Alternate Keys 功能。但首先更正您的模型类设置如下:(正如您所说的 User 将有多个 Document

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    public User Author { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }


    public ICollection<Document> Documents { get; set; }
}

然后在Fluent API配置如下:

modelBuilder.Entity<Document>()
        .HasOne(p => p.Author)
        .WithMany(b => b.Documents)
        .HasForeignKey(p => p.AuthorId)
        .HasPrincipalKey(b => b.AuthUserId); // <-- here you are specifying `AuthUserId` as `PrincipalKey` in the relation which is not primary key

【讨论】:

  • 它是否给了我一个损坏的 JSON 数据(一个方括号,仅此而已)。我在调用文档时使用的方式是这样的。 _dcmsContext.Documents .Include(d =&gt; d.DocumentCategory) .Include(d =&gt; d.DocumentVersions) .Include(d =&gt; d.Author)
  • @Siege21x 这与这里无关。对于预先加载数据和创建代理来说,这是一个单独的问题。使用团队查看器授予我远程访问权限,我正在修复此问题。
  • @Siege21x 也关注这个:stackoverflow.com/a/54633487/5928070
  • 简单的人。我刚完成测试。是的,我很感激你的帮助。谢谢!
  • 但现在的问题是当我使用上面的急切加载时。它使用作者提取所有文档。哪个是对的。但随后在“作者”对象中,它还会提取与作者本身相关的所有文档。
猜你喜欢
  • 2021-11-06
  • 2013-02-08
  • 2020-11-29
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多