开发者

Exception when saving an object with related object EF 3.5

开发者 https://www.devze.com 2023-03-11 13:54 出处:网络
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.

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:

public static Cat GetById(int id)
{
     using (var context = new PhonebookEntities())
     {
          return context.Cats.Single(c => c.Id == id);
     }
}

You are using two different contexts - that is the source of the issue. The first context loads the Cat and fills it EntityKey but the second context doesn't know this instance so once you call AddToCats it will add both new Cat and ParentCat as well but it fails because new entity cannot have filled EntityKey (I know that it is not a new entity but for the new instance of the context it is!).

Add based 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 .Attach for that entity.

Because of that, this is also incorrect:

if (this.ParentCat != null)
{
     if (this.ParentCat.CategoryID == 0)
         context.AddToCats(this.ParentCat);
}

Unknown ParentCat will be added automatically together with the current Cat. If you call this it will also add the current Cat but the next call will try to add it again => you will probably get an exception.

This whole can be solved by two ways:

  • Load the ParentCat on the same context instance as you save Cat
  • Don't load the ParentCat and either use dummy class or try to set EntityKey

Dummy class approach:

var parentCat = new Cat() { Id = 1 };
context.Cats.Attach(parentCat); // Use correct entity set name
var cat = new Cat()
{
    CatName = "Test",
    ParentCat = parentCat
};
cat.Save();

EntityKey aproach (this is more like a guess):

var cat = new Cat()
{
    CatName = "Test",
    // I hope ParentCatReference will be initialized
    ParentCatReference.EntityKey = new EntityKey("Cats", "Id", 1) // Use correct entity set name
};
cat.Save();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号