views:

92

answers:

1

Hi Guys,

This could be a simple solution, but....

If i have a Entity Framework 4 Repository which exposes the following interface:

void InsertOrUpdate(Foo foo);

And my EDM is done with custom POCO's (no code generation), how do i perform UPDATE's to POCO's?

I can INSERT a new object by doing this:

var newFoo = new Foo { ... };
repo.InsertOrUpdate(newFoo);

That works if i implement that method with ObjectContext.AddObject.

But if i try and UPDATE an object:

var existingFoo = repo.Find(foo);
existingFoo.Name = "Changed the foo!";
repo.InsertOrUpdate(existingFoo);

I get an error saying an entity with the same key already exists, which makes sense - but i though the ObjectContext.AddObject method was smart enough to do an INSERT or UPDATE?

How do we handle inserts and updates in EF4 POCO Repos? Do i have to do a query to the DB first to see if it's there, if it isn't then do AddObject, if it is - what do i do?

A: 

So i needed to do SaveChanges on the DataContext, not AddObject when doing Update.

I already had a method called Commit exposed through my DataContext interface, which does a SaveChanges.

I renamed the InsertOrUpdate method to Add.

So now, to INSERT a new entity:

var newFoo = new Foo { ... };
repo.Add(newFoo);

to UPDATE an existing entity:

var existingFoo = repo.Find(foo);
existingFoo.Name = "Changed the foo!";
myCtx.Commit();
RPM1984