1

我有以下课程,一个挑战有很多提交,它也有一个获胜者。问题是,在我的数据库中,实体框架在提交表 [ChallengeId] 和 [Challenge_ChallengeId] 上创建了两列,当我保存一个对象时,它被添加到 ChallengeId 列,但关系被保留在 Challenge_ChallengeId 列上。

我的模型是否存在导致此问题的问题,或者我可以设置某种方式来保持关系并保存到同一列?

谢谢!

public class Submission
 {
    [Key]
    public Int32 SubmissionId { get; set; }

    public DateTime Created { get; set; }

    public Int32 ChallengeId { get; set; }
    [ForeignKey("ChallengeId")]
    public virtual Challenge Challenge { get; set; }
    public String YouTubeVideoCode { get; set; }

    public virtual IList<SubmissionVote> Votes { get; set; }
}

public class Challenge
{
    [Key]
    public Int32 ChallengeId { get; set; }
    [Required]
    public String ChallengeName { get; set; }
    public virtual IList<Submission> Submissions { get; set; }

    public Int32? OverallWinnerId { get; set; }
    [ForeignKey("OverallWinnerId")]
    public virtual Submission OverallWinner { get; set; }

}
4

2 回答 2

1

我认为您可以从仅使用约定以及使用速记关键字作为数据类型中受益。我认为错误是因为您使用 ForeignKey 属性注释了代理。尝试这个

public class Submission
{
    public int SubmissionId { get; set; }
    public DateTime Created { get; set; }
    public int ChallengeId { get; set; }
    public string YouTubeVideoCode { get; set; }

    public virtual Challenge Challenge { get; set; }
    public virtual IList<SubmissionVote> Votes { get; set; }
}

public class Challenge
{
    public int ChallengeId { get; set; }
    [Required]
    public string ChallengeName { get; set; }
    public int? OverallWinnerId { get; set; }

    public virtual Submission OverallWinner { get; set; }
    public virtual IList<Submission> Submissions { get; set; }
}
于 2013-06-20T10:59:02.747 回答
0

我很确定 Entity Framework 使用基于约定的方法,解决此问题的最简单方法是使用Id名称而不是ChallengeIdandSubmissionId

public class Submission
 {
    [Key]
    public Int32 Id { get; set; }

    public DateTime Created { get; set; }

    public Int32 ChallengeId { get; set; }
    [ForeignKey("ChallengeId")]
    public virtual Challenge Challenge { get; set; }
    public String YouTubeVideoCode { get; set; }

    public virtual IList<SubmissionVote> Votes { get; set; }
}

public class Challenge
{
    [Key]
    public Int32 Id { get; set; }

    [Required]
    public String ChallengeName { get; set; }
    public virtual IList<Submission> Submissions { get; set; }

    public Int32? OverallWinnerId { get; set; }
    [ForeignKey("OverallWinnerId")]
    public virtual Submission OverallWinner { get; set; }
}
于 2013-06-20T10:58:32.583 回答