Mimi Müller
Mimi Müller

Reputation: 516

Error An object with the same key already exists in the ObjectStateManager. with ViewModel

i know there are quite a few questions to this error, but i couldnt solve my problem with them.

So i get the error:

InvalidOperationException
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.

I dont even know which key is the same? Can i look that up somehow?

My Controller:

[HttpPost]
public ActionResult Meeting(ViewModel ViewModel)
{
    var ALL = db.Sites.Where(p => p.Content.Any(a => a.Date.CompareTo(DateTime.Now) <= 0)).OrderBy(l => l.Customer.Service).ToList();

    //Adding informations that arnt added by user
    ViewModel.Changing.LastUpdate = DateTime.Now;
    ViewModel.Changing.LastUpdaterId = UpdaterID;
    Site current = ViewModel.Changing;


    if (ModelState.IsValid)
    {
        db.Entry(current).State = EntityState.Modified; //Here is the error
        db.SaveChanges();
    }
    //... 
}

My ViewModel

public class ViewModel
{
    public managementtool.Models.Site Changing { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
    public List<managementtool.Models.Issue> OpenIssue { get; set; }
    public List<managementtool.Models.Issue> ClosedIssue { get; set; }
    public managementtool.Models.Site Site { get; set; }
    public int ID { get; set; }
}

I would be grateful for youre help.

Upvotes: 0

Views: 410

Answers (1)

Mimi M&#252;ller
Mimi M&#252;ller

Reputation: 516

Unfortunately i used the Site Model in that Action before like this:

[HttpPost]
public ActionResult Meeting(ViewModel ViewModel)
{
//The Error appears if the following part isnt commented out -->
//var ALL = db.Sites.Where(p => p.Content.Any(a => a.Date.CompareTo(DateTime.Now) <= 0)).OrderBy(l => l.Customer.Service).ToList();


//Adding informations that arnt added by user
ViewModel.Changing.LastUpdate = DateTime.Now;
ViewModel.Changing.LastUpdaterId = UpdaterID;
Site current = ViewModel.Changing;


if (ModelState.IsValid)
{
    db.Entry(current).State = EntityState.Modified; //Here is the error
    db.SaveChanges();
}
//... 
}

So there was the second key, so the ObjectStateManager couldnt track multiple objects with the same key.

Upvotes: 0

Related Questions