views:

129

answers:

1

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();
    }
+1  A: 

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();
}
Buu Nguyen
You are right, I don't know what I was thinking. I should use the getObject method instead of re-typing the same query, thanks. I haven't implement the generic get, but I will as soon as I get some other features done. Thanks again.
Geo