【问题标题】:Entity Framework Core - How to correctly define primary key that is also a foreign key?Entity Framework Core - 如何正确定义也是外键的主键?
【发布时间】:2019-09-24 00:13:23
【问题描述】:

我有以下实体:

class Topic {
    public int TopicId { get; set; }
}

public class Post {
   public int PostId { get; set; }
   public int TopicId { get; set; } 
}

Topic.TopicId 和 Post.PostId 基于名为“PostIdSequence”的 SQL 序列。如果 TopicId 和 PostId 相同,则表示该特定帖子是“主题帖子”。

我希望在创建新的“主题”时能够做这样的事情(这应该有一个具有相同 PostId 和 TopicId 的匹配帖子):

var topic = new Topic() {};
var post = new Post() {};
DbContext.Topics.Add(topic);
DbContext.Posts.Add(post);
DbContext.SaveChanges();

所以基本上,它应该使用 PostIdSequence 的下一个值自动填充“Topic.TopicId”,然后将其分配给 Post.PostId。

创建这些实体类的“正确”方式是什么?

【问题讨论】:

  • 您需要通过您分配的对象上的属性通知 EF PostTopic 相关,而不仅仅是 TopicId

标签: entity-framework entity-framework-core


【解决方案1】:

如果我错了,请纠正我.. 根据我的理解,我认为您违反了 SQL 基本...

你不能将PK作为FK,也不能在同一张桌子上进行超过1个PK。

要解决您的问题,您必须声明最多 1 个 PK 和 1 个或超过 1 个 FK。

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }

    //Foreign key for Standard
    public int StandardId { get; set; }
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }

    public ICollection<Student> Students { get; set; }
}

如果您有任何疑问,请随时询问。

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 2016-12-16
    • 2018-09-28
    • 2021-02-04
    相关资源
    最近更新 更多