Add an EF object as a foreign key

advertisements

Ok, I've been pulling my hair out over this for a few days now.

How do I instruct entity framework to insert an object as a foreign key to an existing object, rather than as an entirely new object? I have tried all sorts of things. I keep getting the error "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

I'm just trying to add a country to an address. The countries are all listed in a separate database table. The country comes from a dropdown list posted from an MVC view so I only have the ID. This means the only way I can get the object is to query EF which results in a duplicate object.

Hope someone can help. Aaarg!

M

=== More info ===

While the above points out quite correctly to just set the countryID, this only works for create scenarios. It doesn't work for edit.

I have this in my controller:

    public ActionResult Edit(SiteViewModel siteViewModel)
    {
        if (ModelState.IsValid)
        {
            Site site = _unitOfWork.SiteRepository.GetById(siteViewModel.SiteID);
            _unitOfWork.Detach(site);
            site = Mapper.Map<SiteViewModel, Site>(siteViewModel);
            site.CountryId = siteViewModel.CountryId;
            ...
        }
    }

I am still now getting the multiple objects with the same key error. How do I detach the country so I can re-add it again (!) without removing it from the database??

Please help!

M


try:

var id = 2; // id of item 

using (var context = new Context())
      {
            var item = context.YourTable.Single(m => m.Id== id);

            item.ForeinKey = someNewForeinKey;

            context.SubmitChanges();
      }