2017-10-07 13 views
0

爲了簡單起見,我們來考慮一個模仿StackOverflow的問題的簡單場景。如何將Vote實體模型配置爲具有複合PK?

  • 每個用戶可以發佈零個或多個問題。
  • 每個問題可以有零個或多個選票。
  • 每個用戶可以選擇每個問題僅投一次。
  • 爲了簡單起見,讓發佈問題投票的用戶自己的問題。該功能將在稍後移除。
public class User 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public IEnumerable<Question> Questions { get; set; } 
    public IEnumerable<Vote> Votes { get; set; } 
} 

public class Question 
{ 
    public int Id { get; set; } 
    public string Content { get; set; } 

    public User User { get; set; } // the user to whom the question belongs 
    public int UserId { get; set; } 

    public IEnumerable<Vote> Votes { get; set; } 
} 


public class Vote 
{ 
    public bool IsUp { get; set; } // true = upvote or false = downvote 

    public User User { get; set; }// the user who votes a question 
    public int UserId { get; set; } 

    public Question Post { get; set; }// the question for which this vote is intended 
    public int QuestionId { get; set; } 
} 

問題

如何確保沒有用戶誰票同一個問題的兩倍以上?我是新手!如果我的實體模型實際上太差,歡迎任何建議或改進!

回答

1

你需要把它們列的順序,SQL服務器將映射它
下面是一個例子

public class Vote 
{ 
    [Key, Column(Order = 0)] 
    public string UserID { get; set; } 

    [Key, Column(Order = 1)] 
    public int QuestionID { get; set; } 
} 
+0

雖然這是EF6一種有效的方法,它並不適用於EF核心。 –

相關問題