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


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

If I have an entity framework 4 is the repository which highlights the following interface:

  Zero InsertOrUpdate (Foo foo);  

And my ADM is done with custom Poko (no code generation), how do I update POCO?

I create a new object by doing INSERT :

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

This works if I implement that method with ObjectContext.AddObject .

But if I try and UPDATE an object:

  var current Foo = repo.Find (foo); Existing Foo.Name = "Change foo!"; Repo.InsertOrUpdate (existingFoo);  

I get an error, which is already present with the same key with one unit, which is understandable - but I though ObjectContext.AddObject The method was quite efficient INSERT or UPDATE?

How do we manage to add and update EF4 POCO Reposes? Do I have to ask DB first to see if he is there, if he is not, AddObject, if it is - what do I have to do?

So I had to do SaveChanges on DataChontext, not addObject when updating.

I already had a method called Commit was conveyed to my datacentext interface, which changes to a save.

I named the InsertOrUpdate method Add .

So now, to INSERT a new unit:

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

To update an existing unit:

  var current Foo = repo.Find (foo); Existing Foo.Name = "Change foo!"; MyCtx.Commit ();  

Comments