Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

c# - The entity type List`1 is not part of the model for the current context

I've been using Database First, EF 4.1

I am getting "The entity type List`1 is not part of the model for the current context." error when trying to update a record from my Edit View.

The error is occurring at

db.Entry(properties).State = EntityState.Modified;

Here is my Model:

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; }
}

Here is my Controller:

[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);
}

I suspect the foreach loop is not appropriate in setting the EntityState for each item in an ICollection.

Any assistance would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try changing your loop to:

foreach (var item in properties)
{
     db.Entry(item).State = EntityState.Modified;
}

You were calling db.Entry(properties), so you were trying to attach the whole collection at once. DbContext.Entry(object) expects a single object, not a collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...