开发者

Entity Framework 4 POCO CRUD Repository - How to perform Smart INSERT/UPDATE?

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 t开发者_高级运维o see if it's there, if it isn't then do AddObject, if it is - what do i do?


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();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜