What is the best way to update an unattached entity on Entity Framework?
- by Carlos Loth
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.