我有一个主表 - 问题和详细信息表 - 答案。一个问题可以有多个答案。使用Entity Framework插入答案的正确方法是什么?
[Table("question")]
public class Question
{
[Key]
[Column("idquestion")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("locked")]
public bool Locked { get; set; }
[Column("answered")]
public bool Answered { get; set; }
[Column("skipped")]
public bool Skipped { get; set; }
[Column("skipped_emails")]
public string SkippedEmails { get; set; }
[Column("idspecialty")]
public int? SpecialtyId { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
答案表:
[Table("answer")]
public class Answer
{
[Key]
[Column("idanswer")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("answered_by")]
public string AnsweredBy { get; set; }
[Column("answered_on")]
public DateTime? AnsweredOn { get; set; }
[Column("idquestion")]
[ForeignKey("Question")]
public int QuestionId { get; set; }
public Question Question { get; set; }
}
我在代码表中插入行的代码不起作用:
using(var context = new QnAContext())
{
var answer = new Answer();
answer.Name = tbAnswer.Text;
answer.AnsweredBy = this.User.Identity.Name;
answer.AnsweredOn = DateTime.Now;
int questionId = int.Parse(hdnQuestion.Value);
var question = context.Questions.SingleOrDefault(q => q.Id == questionId);
if(question!=null)
{
question.SpecialtyId = int.Parse(ddlSpecialty.SelectedItem.Value);
question.Answered = true;
answer.Question = question;
}
context.SaveChanges();
}
答案 0 :(得分:1)
将answer.Question = question;
替换为question.Answers.Add(answer);
,并确保将.Include(q => q.Answers)
放在上下文的Questions
集合中,即:
int questionId = int.Parse(hdnQuestion.Value);
var answer = new Answer
{
Name = tbAnswer.Text,
AnsweredBy = this.User.Identity.Name,
AnsweredOn = DateTime.Now
};
using(var context = new QnAContext())
{
for (var question in context.Questions
.Include(q => q.Answers)
.Where(q => q.Id == questionId))
{
question.SpecialtyId = int.Parse(ddlSpecialty.SelectedItem.Value);
question.Answered = true;
question.Answers.Add(answer);
}
context.SaveChanges();
}