I'm working on a website on ASP.NET MVC4 and EF5. I want to ensure that only modified values are updated in the database. I'm using a unit of work pattern and repositories for data work. Here's the code for a generic repository. I've two questions, and need a code review for the following code.
Is the code to update only modified fields good? It works, but I don't know if this is the best way. I especially don't like that I have to do this loop through the properties myself (can't EF do this?). I also don't like the cast to object and the comparison.
How are my Add and Update methods? I'm planning the clients (MVC/API controllers) to use a service (passing in a unit of work) to get the work done. They will not directly use the repository. The repository will not have a Save() method, only the UnitOfWork will have one. I can ensure within the service that I will use the same context to update/add entities. Given this, are there any scenarios where my Add/Update code is going to fail?
public class EFRepository<T> : IRepository<T> where T : class
{
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public EFRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
DbContext.Entry(entity).State = EntityState.Added;
}
public virtual void Update(T entity)
{
//dbEntityEntry.State = EntityState.Modified; --- I cannot do this.
//Ensure only modified fields are updated.
var dbEntityEntry = DbContext.Entry(entity);
foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
{
var original = dbEntityEntry.OriginalValues.GetValue<object>(property);
var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
if (original != null && !original.Equals(current))
dbEntityEntry.Property(property).IsModified = true;
}
}
//... Other methods ...
}