使用实体框架添加详细信息行
本文关键字:详细信息 添加 框架 实体 | 更新日期: 2024-11-06 06:22:00
我有一个主表 - 问题和详细表 - 答案。一个问题可以有多个答案。使用实体框架插入答案的正确方法是什么?
[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("answerswered")]
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("answerswer")]
public class Answer
{
[Key]
[Column("idanswer")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("answerswered_by")]
public string AnsweredBy { get; set; }
[Column("answerswered_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();
}
将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();
}