在 SaveChanges() 之前修改模型
这是我的问题的超简化版本,但它直奔主题。
我有这个模型
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public string AnswerText { get; set; }
现在,假设我想在 SaveChanges() 之前将 AnswerText 修改为“blah blah”控制器:
[HttpPost]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
question.AnswerText = "blah blah"
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
这按预期工作。
现在,代替 public string AnswerText { get;放;我想要一个答案列表:
public List<string> AnswersText { get; set; }
并且我想在 SaveChanges() 之前手动添加答案:
[HttpPost]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
question.AnswersText = new List<string>();
question.AnswersText.Add("blah1");
question.AnswersText.Add("blah2");
question.AnswersText.Add("blah3");
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
我得到的很奇怪:我的问题已正确添加到上下文中,但答案列表始终为空。我不知道该怎么做,这对我来说似乎是一个简单的任务。
感谢您的帮助。
This is an ultra-simplified version of my problem but it gets straight to the point.
I have this model
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public string AnswerText { get; set; }
Now, imagine I want to modify the AnswerText to "blah blah" just before SaveChanges() in the controller:
[HttpPost]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
question.AnswerText = "blah blah"
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
This works as expected.
Now, in place of public string AnswerText { get; set; } I want a list of answers:
public List<string> AnswersText { get; set; }
And I want to manually add answers just before SaveChanges():
[HttpPost]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
question.AnswersText = new List<string>();
question.AnswersText.Add("blah1");
question.AnswersText.Add("blah2");
question.AnswersText.Add("blah3");
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
What I get is weird: My question is correctly added to the context but the list of answers is always empty. I don't know what to do, it seems such a simple task to me.
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能期望实体框架具有 List 属性并知道如何存储它。您需要创建一个答案实体并使用它:
现在在问题中:
它将把问题及其答案存储为单独的表。单个问题的每个答案都会有自己的单独行。
You can't expect entity framework to have a List property and know how to store that. You need to create a Answer entity and use that instead:
now in Question:
It will store questions and their answers as a separate table. Each answer to a single question will get its own individual row.