所有
我正在尝试在我的模型中保存一个对象列表,当我逐步执行它时,执行着陆
db.Entry(model.Sponsors).State = EntityState.Modified;
然后被抓住了:
实体类型List`1不是当前上下文模型的一部分。
列表在视图模型中声明,数据被拉入视图确定。这是我保存数据时发生的情况。我该如何解决?
包含表单的视图
for (var i = 0; i < Model.Sponsors.Count; i++)
{
string sponsorDivId = "sponsorclubname" + i.ToString();
string deleteLink = "<a class=\"icon delete cosponsor\" data-attr-divid=\""+@sponsorDivId+"\" data-attr-id=" + @Model.Sponsors[i].Id + "></a>";
<div id="@sponsorDivId">
@Html.HiddenFor(x => x.Sponsors[i].Id)
<div class="formColumn1"><label for="sponsorclubname1">Sponsor club name</label></div>
<div class="formColumn2">@Html.EditorFor(x => x.Sponsors[i].SponsorContactName)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactName)
</div>
</div>
<div class="formColumn3">@Html.EditorFor(x => x.Sponsors[i].SponsorContactEmail)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactEmail)
</div>
</div>
<div class="formColumn4">@Html.EditorFor(x => x.Sponsors[i].SponsorContactPhone)@(i > 0 ? Html.Raw(deleteLink) : Html.Raw(""))
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactPhone)
</div>
</div>
</div>
<div class="clear"></div>
}
视图模型中列表的声明
public List<NewClubSponsor> Sponsors { get; set; }
执行处理的控制器
[HttpPost]
public ActionResult ProcessFormANewClubTeam(FormANewClubTeamViewModel model)
{
if (ModelState.IsValid)
{
try
{
db.Entry(model.Sponsors).State = EntityState.Modified;
db.SaveChanges();
}
catch (Exception ex)
{
{
var err = "Error: " + ex.ToString();
Console.WriteLine("Error: "+ err);
}
}
}
[...]
}
答案 0 :(得分:1)
它的含义是List<NewClubSponsor>
不是由您的数据库或代码生成的模型。
您真正想要的是保存个人NewClubSponsor
,因此您需要更改每个对象的状态。您还只想更改现有对象的对象状态。你想添加新的。
foreach(var sponser in model.Sponsors)
{
if(sponser.ID <= 0)
{
db.Sponsors.Add(sponser);
}
else if(db.Entry(sponser).State == EntityState.Detached)
{
db.Sponsors.Attach(sponser);
db.Entry(sponser).State = EntityState.Modified;
}
}
db.SaveChanges();