Isa*_*lee 23 c# entity-framework-4.1 asp.net-mvc-3
我一直在使用Database First,EF 4.1
我得到"实体类型List`1不是当前上下文模型的一部分." 尝试从"编辑视图"更新记录时出错.
错误发生在
db.Entry(properties).State = EntityState.Modified;
Run Code Online (Sandbox Code Playgroud)
这是我的模型:
public class Users
{
[Key]
public int User_ID { get; set; }
public string UserName { get; set; }
[NotMapped]
public IEnumerable<App_Properties> User_Properties
{
get { return Properties.Where(u => u.User_ID == User_ID); }
}
public virtual ICollection<App_Properties> Properties { get; set; }
}
public class App_Properties
{
[Key]
public int Prop_ID { get; set; }
public int User_ID { get; set; }
public int App_ID { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public DateTime DateEntered { get; set; }
public DateTime DateModified { get; set; }
[ForeignKey("User_ID")]
public virtual Users Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
[HttpPost]
public ActionResult Edit(ICollection<App_Properties> properties)
{
if (ModelState.IsValid)
{
foreach (var item in properties)
{
db.Entry(properties).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(properties);
}
Run Code Online (Sandbox Code Playgroud)
我怀疑foreach循环不适合为ICollection中的每个项设置EntityState.
任何帮助将不胜感激.
Len*_*ncy 57
尝试将循环更改为:
foreach (var item in properties)
{
db.Entry(item).State = EntityState.Modified;
}
Run Code Online (Sandbox Code Playgroud)
你在打电话db.Entry(properties)
,所以你试图立刻附上整个收藏品.DbContext.Entry(object)需要单个对象,而不是集合.
Jon*_*han 11
谢谢,宽大,答案.工作得很好.
为了它的价值,我更喜欢将我的EntityState.Modified
作业保留在一行(因为我有多个)所以使用以下LINQ:
properties.ForEach(p => db.Entry(p).State = EntityState.Modified);
Run Code Online (Sandbox Code Playgroud)