【问题标题】:What is the foreign key if more than one pair of navigation properties exists?如果存在不止一对导航属性,那么外键是什么?
【发布时间】:2019-08-03 15:53:45
【问题描述】:

以下内容来自官方文档。

您可以使用数据注释来配置导航方式 从属实体和主体实体上的属性配对。这是 通常在有一对以上导航时完成 两种实体类型之间的属性。

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int AuthorUserId { get; set; }
    public User Author { get; set; }

    public int ContributorUserId { get; set; }
    public User Contributor { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [InverseProperty("Author")]
    public List<Post> AuthoredPosts { get; set; }

    [InverseProperty("Contributor")]
    public List<Post> ContributedToPosts { get; set; }
}

问题

由于我是 EF Core 新手,如果存在不止一对导航属性,那么外键是什么?

【问题讨论】:

  • @HenkHolterman:太短了,无法理解。对不起。
  • 您的问题应该改写为 what are 外键s ... - Post 类包含两个 FK - 一个用于作者,一个用于贡献者
  • @SirRufo:我不知道在两个表之间的关系中可能有 2 个外键。
  • 两个表之间可能有 n 个外键(理论上 - 它受数据库系统每个表的最大字段数限制)

标签: c# entity-framework-core


【解决方案1】:

您的代码将以这种方式工作,

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    [ForeignKey("Author")]
    public int AuthorUserId { get; set; }
    public virtual User Author { get; set; }

    [ForeignKey("Contributor")]
    public int ContributorUserId { get; set; }
    public virtual User Contributor { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [InverseProperty("Author")]
    public ICollection<Post> AuthoredPosts { get; set; }

    [InverseProperty("Contributor")]
    public ICollection<Post> ContributedToPosts { get; set; }
}

干杯,

【讨论】:

  • 您确定将 `[ForeignKey("Author")]` 属性附加到 AuthorUserId 属性,而不是将 `[ForeignKey("AuthorUserId")]` 附加到 Author 属性吗?
  • 此外,如果您有外键属性名称,如 AuthorId 和 ContributorId,您可能根本不需要 ForeignKey 属性。即 Id EF 按约定确定外键。
  • 这可能是另一种方式。我建议的方式是我们过去的方式,我有很多工作代码。
  • 好的。让其他人在几天后确认这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多