I get an error telling me that: “The EntityKey property can only be set when the current value of the property is null.” when I try to save an object with related object.
Here’s my code:
public partial class Cat{
public bool Save()
{
try
{
using (var context = new PhonebookEntities())
{
if (this.ParentCat != null)
{
if (this.ParentCat.CategoryID == 0)
context.AddToCats(this.ParentCat);
}
context.AddToCats(this);
context.SaveChanges();
}
return true;
}
catch (System.Exception)
{
return false;
}
}
And here I create a Cat object and connect it to a relatet parent Cat object and then call the save method:
var cat = new Cat()
{
CatName = "Test",
ParentCat = Cat.GetById(1)
};
cat.Save();
Let me guess – the
Cat.GetById(1)looks like:You are using two different contexts – that is the source of the issue. The first context loads the Cat and fills it
EntityKeybut the second context doesn’t know this instance so once you callAddToCatsit will add both newCatandParentCatas well but it fails because new entity cannot have filledEntityKey(I know that it is not a new entity but for the new instance of the context it is!).Addbased operations always add all unknown entities in the object graph. The entity is known by the context only if the same context loaded the entity or if you called.Attachfor that entity.Because of that, this is also incorrect:
Unknown
ParentCatwill be added automatically together with the currentCat. If you call this it will also add the currentCatbut the next call will try to add it again => you will probably get an exception.This whole can be solved by two ways:
ParentCaton the same context instance as you saveCatParentCatand either use dummy class or try to setEntityKeyDummy class approach:
EntityKeyaproach (this is more like a guess):