我有 3 个实体:问题
public enum QuestionType
{
Scenario,
Step
}
public class Question
{
public int Id { get; set; }
public int CategoryId { get; set; }
[Required] [MaxLength(255)] public string Text { get; set; }
[MaxLength(255)] public string FrameText { get; set; }
public int Order { get; set; }
public QuestionType Type { get; set; }
public DefaultAnswer DefaultAnswer { get; set; }
public IList<Answer> Answers { get; set; }
}
回答
public class Answer
{
public int Id { get; set; }
public int QuestionId { get; set; }
[Required] [MaxLength(255)] public string Text { get; set; }
public int Order { get; set; }
public Scenario Scenario { get; set; }
public IList<Formula> Formulas { get; set; }
public IList<Image> Images { get; set; }
}
最后,DefaultAnswer:
public class DefaultAnswer
{
public int QuestionId { get; set; }
public int AnswerId { get; set; }
public Answer Answer { get; set; }
public Question Question { get; set; }
}
之间的关系问题和答案是显而易见的。我想为一个问题设置一个DefaultAnswer,所以我DefaultAnswer在Question模型中添加了一个导航属性。这是可选的,因为它可以为空。
所以,我试图建立这样的关系:
modelBuilder.Entity<DefaultAnswer>().HasKey(m => new { m.QuestionId, m.AnswerId });
modelBuilder.Entity<Question>().HasOptional(m => m.DefaultAnswer).WithRequired(m => m.Question);
modelBuilder.Entity<DefaultAnswer>().HasRequired(m => m.Answer).WithMany().HasForeignKey(m => m.AnswerId);
但这不起作用,它会Question_Id在DefaultAnswers表中创建另一个名为的字段..... 这就是 EF 生成的内容:
public override void Up()
{
CreateTable(
"dbo.DefaultAnswers",
c => new
{
QuestionId = c.Int(nullable: false),
AnswerId = c.Int(nullable: false),
Question_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.QuestionId, t.AnswerId })
.ForeignKey("dbo.Answers", t => t.AnswerId, cascadeDelete: true)
.ForeignKey("dbo.Questions", t => t.Question_Id)
.Index(t => t.AnswerId)
.Index(t => t.Question_Id);
}
有谁知道我如何创建这种关系,同时仍将导航属性保留在Question 中?
慕妹3146593
料青山看我应如是
相关分类