ADO.NET Entity Framework : Editing a detached Object
In Layered scenario, you might need to pass an object to another method while updating. Carrying open Context is not good however you may try the below approach by using “CreateEntityKey”. But this will not work if you have configured your edmx with Stored Procedure, reason behind that is
static void Main(string[] args)
{
//Create Entity Key Object
EntityKey key;
object originalItem;
//This object can come through method parameter
Emp updatedItem = new Emp() { Id = 190 };
updatedItem.FirstName = "Changed Last Name";
using (TestDBEntities ctx = new TestDBEntities())
{
key = ctx.CreateEntityKey("Emp", updatedItem);
if(ctx.TryGetObjectByKey(key, out originalItem))
{
ctx.ApplyPropertyChanges(key.EntitySetName, updatedItem);
}
ctx.SaveChanges();
}
}
Namoskar!!!
Comments
Anonymous
April 23, 2009
PingBack from http://asp-net-hosting.simplynetdev.com/adonet-entity-framework-editing-a-detached-object/Anonymous
May 30, 2009
Wriju, How does the method you describe compare to the method described at http://blogs.msdn.com/dsimmons/archive/2008/10/31/attachasmodified-a-small-step-toward-simplifying-ef-n-tier-patterns.aspx? Thanks, Sven.Anonymous
May 30, 2009
@Sven, There are a lot og diff. When I tried to use Attach method the way I use it in L2S, I found the above difference. So I wrote the blog. The URL you have mentione is more of a n-tier scenario.