复合密钥和分离的身份密钥

时间:2016-04-16 19:06:47

标签: c# entity-framework many-to-many

请阅读该问题:Create code first, many to many, with additional fields in association table

以下是OP的情景:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<Member> Members { get; set; }
}

public class MemberComment
{
    public int MemberID { get; set; }
    public int CommentID { get; set; }
    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

接受的答案是:

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

现在,我的问题是:如果我想添加另一个身份字段,例如Guid或AutoInc int ,例如:

    public int MemberCommentID { get; set; }

我不是在讨论它是更好的方法还是不,我想知道我是怎么做的?

我在想这样的事情

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberCommentID { get; set; }

    [Key, Column(Order = 1)]
    public int MemberID { get; set; }
    [Key, Column(Order = 2)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

但是EF(我认为)将使用密钥中的3个字段,当右边是MemberCommentID时,单独使用1个密钥,而MemberID + CommentID是另一个密钥。

1 个答案:

答案 0 :(得分:1)

在这种情况下,为什么不在MemberIDCommentID上使用ForeignKey

public class MemberComment
{
    [Key]
    public int MemberCommentID { get; set; }

    [ForeignKey]
    public int MemberID { get; set; }
    [ForeignKey]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

正如您所看到的,它实际上允许您重复MemberComment个(连接相同的成员和注释实例)。

如果您希望强制MemberComment只能链接一次,那么您可以使用Unique Constraint来实现它。

但如果这是您的要求(每个成员评论对一个成员评论),那么您为什么要添加MemberCommentID密钥?

MemberID, CommentID完美且自然的主键,可以完成所有工作而无需额外的字段/索引。