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();
}
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:
Now, your above code should be