问题描述
[HttpPost]
public ActionResult Solution(List<Questionsmodel> model)
{
if (ModelState.IsValid)
{
ALBulkTestResult obj = new ALBulkTestResult();
var now = DateTime.Now;
var date = new DateTime(now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second);
foreach (QuestionsModel ans in model)
{
obj.TestID = ans.TestId;
obj.SkillID = ans.SkillId;
obj.QuestionID = ans.ID;
obj.CandidateAns = ans.SelectedAnswer;
obj.TestDate = date;
}
//db.Entry(obj).State = EntityState.Modified;
db.ALBulkTestResults.Add(obj);
db.SaveChanges();
}
return RedirectToAction("Successfull");
}
这是保存多条记录的权利。请更正我..
这里我收到错误
EntityFramework.dll中出现'System.Data.Entity.Infrastructure.DbUpdateException'类型的例外但不是用户代码处理附加信息:更新条目时发生错误。有关详细信息,请参阅内部异常。
this is the right wasy to the save multiple records. Please correct me..
Here i'm getting error
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code Additional information: An error occurred while updating the entries. See the inner exception for details.
the insert statement conflicted with the foreign key constraint entity framework
推荐答案
var now = DateTime.Now;
var date = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
这条线不是更好吗?
wouldn't it be better to just have this line?
DateTime date = DateTime.Now;
也许我错过了什么,但我看不出你会怎样使用此代码保存多个结果
Maybe I am missing something, but I fail to see how you will save more than one result using this code
foreach (QuestionsModel ans in model)
{
obj.TestID = ans.TestId;
obj.SkillID = ans.SkillId;
obj.QuestionID = ans.ID;
obj.CandidateAns = ans.SelectedAnswer;
obj.TestDate = date;
}
对于循环的每次迭代,您更改单个实例的属性 obj
这不应该是一个数组吗?
至于你得到的错误。
你试过吗?跳过循环只保存一行?
因为你没有显示你的表结构,我只能猜测 ans.ID
是一个外键和此ID不存在。
For each iteration of the loop, you change the properties of the single instance obj
Shouldn't this be an array?
As for the error you get.
Have you tried to skip the loop and just save one row?
As you don't show your table structure, I can only guess that ans.ID
is a foreign key and this ID doesn't exist.
这篇关于保存多个问题和答案记录时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!