With Repository pattern, what is the most effective way of updating records?
-
07-07-2019 - |
Question
I am implementing Repository Pattern with ADO.NET entity framework. I see that updating records is relatively more complicated than just adding or removing from the database. See below the Update statement and add statement for your judgment.
I was wondering if there is any way that I can update the record without having to retreive the original record first.
public void Update(User user)
{
var userToUpdate = (from u in db.UserSet
where u.UserID == user.UserID
select u).FirstOrDefault(); //original record
db.ApplyPropertyChanges(userToUpdate.EntityKey.EntitySetName,
user);
db.SaveChanges();
}
Add statement for the same repo:
public void Add(User user)
{
user.MemberFrom = DateTime.Now;
_repository.AddToUserSet(user);
_repository.SaveChanges();
}
Solution
No, you can't do that with EF (unless you use ADO.NET directly of course). That said, you can simplify the retrieval code by adding some methods to the partial class of your entity context. This is how I do it:
public partial class MyEntities
{
public T GetById<T>(object id) where T : class
{
EntityKey key = CreateKey<T>(id);
// see http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.getobjectbykey.aspx
return (T)GetObjectByKey(key);
}
public static EntityKey CreateKey<T>(object id)
{
var type = typeof(T);
return new EntityKey("MyEntities." + type.Name, "Id", id);
}
}
Now, your above code should be
public void Update(User user)
{
var userToUpdate = db.GetById<UserSet>(user.UserID);
db.ApplyPropertyChanges(userToUpdate.EntityKey.EntitySetName, user);
db.SaveChanges();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow