EF4 adding multiple objects (an object with the same key already exists in ObjectStateManager)

I have an object with a lot of properties on it. A bunch of these large objects should be inserted in db, but with a change in only one property. The property that will change is not the primary key. The first time SaveChanges succeeds, but the subsequent ones do not work: "An object with the same key already exists in ObjectStateManager ....." Here is the stream in the code:

    //create the entity and set the properties that don't change
    TheLargeObject obj = new TheLargeObject();
    obj.Prop1 = 
    obj.Prop2 = 
    ...
    obj.Prop20 = 

    //create a list of values that differ between each entity
    List<int> validIds = new List<int>();

    private static void SaveToDatabase(TheLargeObject obj, List<int> validIds)
    {

        foreach (int id in validIds)
        {
            //this is the only property that changes
            obj.KeyId = id;

            //make a copy - do we really need this?
            TheLargeObject newobj = new TheLargeObject();
            newobj = obj;

            using(Entities objContext = new Entities())
            {
                objContext.TheLargeObjects.AddObject(newobj); //ERROR: An object with the same key already exists in the ObjectStateManager.  
                objContext.SaveChanges();
            }
        }
    }

I am just starting out with EF4, so probably I'm wrong. Thanks

+3
source share
1 answer

I'm not sure what you are trying to do here. Basically this expression confuses me:

​​ db, .

(.. ) ? , ?

EntityKey, .

, .AddObject, .Attach.

INSERT :

var newFoo = new Foo();
ctx.Foos.AddObject(newFoo);
newFoo.SaveChanges();

UPDATE :

var existingFoo = ctx.Foos.SingleOrDefault(x => x.Id == 1); // or however you want to get it
existingFoo.Name = "Changed foo";
newFoo.SaveChanges();

:

var existingFoo = new Foo();
existingFoo.Name = "Foo name";
ctx.Foos.Attach(existingFoo);
ctx.SaveChanges();

, , :

objContext.TheLargeObjects.Attach(newObject);
objContext.SaveChanges();

, , , , , .Attach. , , .AddObject.

, - , .SaveChanges().

.Attach , -, , .Attach .

, .

+8

Source: https://habr.com/ru/post/1775347/


All Articles