seeker
seeker

Reputation: 3333

twice attaching same entity

I want to implement a kind of AddOrUpdate method functionality. Therefore I write the following code for each entity add or update:

var someEntity =
                    context.Set<SomeEntity>.FirstOrDefault(
                        x => x.EntityId == 2) ?? new SomeEntity();

        context.Set<SomeEntity>().Attach(someEntity);
        someEntity.Foo="foo";
        someEntity.Bar="Bar";
//...
context.SaveChanges(); 

While using that code, when entity that satisfies conditiob exists, it is duplicated. Could you advice what am I missing. In my understanding if we are attaching to already attached entity it states doesn't change.

Upvotes: 1

Views: 1053

Answers (1)

Guillaume
Guillaume

Reputation: 13138

You should specify the EntityState :

var someEntity =
                context.Set<SomeEntity>.FirstOrDefault(
                    x => x.EntityId == 2) ?? new ProcedureBillingOptionRecord();

context.Entry(someEntity).State = someEntity.EntityId == 0 ? 
                                   EntityState.Added : 
                                   EntityState.Modified; 
someEntity.Foo="foo";
someEntity.Bar="Bar";
//...
context.SaveChanges(); 

Source : Add/Attach and Entity States, Insert or update pattern

Upvotes: 1

Related Questions