What is the best way to update an unattached entity on Entity Framework?
Posted
by Carlos Loth
on Stack Overflow
See other posts from Stack Overflow
or by Carlos Loth
Published on 2010-03-26T18:21:16Z
Indexed on
2010/03/26
18:23 UTC
Read the original article
Hit count: 434
Hi,
In my project I have some data classes to retrieve data from the database using the Entity Framework. We called these classes *EntityName*Manager. All of them have a method to retrieve entities from database and they behave most like this:
static public EntityA SelectByName(String name)
{
using (var context = new ApplicationContext())
{
var query =
from a in context.EntityASet
where a.Name == name
select a;
try
{
var entityA = query.First();
context.Detach(entityA);
return entityA;
}
catch (InvalidOperationException ex)
{
throw new DataLayerException(
String.Format("The entityA whose name is '{0}' was not found.", name),
ex);
}
}
}
You can see that I detach the entity before return it to the method caller. So, my question is "what is the best way to create an update method on my *EntityA*Manager class?"
I'd like to pass the modified entity as a parameter of the method. But I haven't figured out a way of doing it without going to the database and reload the entity and update its values inside a new context.
Any ideas?
Thanks in advance, Carlos Loth.
© Stack Overflow or respective owner