【问题标题】:How to configure the Vote entity model to have a composite PK? [duplicate]如何配置投票实体模型进行复合 PK? [复制]
【发布时间】:2017-10-07 16:27:57
【问题描述】:

为了简单起见,让我们考虑一个模仿 StackOverflow 问题的简单场景。

  • 每个用户可以发布零个或多个问题。
  • 每个问题可以有零票或多票。
  • 每个用户可以选择每个问题只投票一次。
  • 为简单起见,让发布问题的用户投票他/她自己的问题。稍后将删除此功能。
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; }
}

问题

如何确保没有用户对同一问题投票两次或多次?我是新手!如果我的实体模型实用性太差,欢迎提出任何建议或改进!

【问题讨论】:

    标签: c# entity-framework entity-framework-core


    【解决方案1】:

    您需要将它们按列顺序排列,然后 SQL Server 将对其进行映射
    这是一个例子

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

    【讨论】:

    • 虽然这对于 EF6 是一种有效的方法,但它不适用于 EF Core。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-10-17
    相关资源
    最近更新 更多