//
////1
public Task ReservedQuantity(long productId, long skuId, int reservedQuantity, long userId) {
return Update<Inventory>(i => new Inventory {
ReservedQuantity = i.ReservedQuantity + reservedQuantity,
AvaliableQuantity = i.AvaliableQuantity - reservedQuantity,
LastModifiedTime = DateTimeOffset.Now,
LastModifiedUserId = userId
}, i => i.SkuId == skuId);
}
protected Task<bool> Add<TModel>(TModel entity, Expression<Func<TModel, bool>> existsChecker = null) where TModel : class, IEntity {
return _context.Add(entity, existsChecker);
}
protected Task<int> Update<TModel>(Expression<Func<TModel, TModel>> updateProperties, Expression<Func<TModel, bool>> @where) where TModel : class, IEntity {
return _context.Update(updateProperties, @where);
}
protected Task<int> Delete<TModel>(Expression<Func<TModel, bool>> @where) where TModel : class, IEntity {
return _context.Delete(@where);
}
--//2
public void Update(T obj, params Expression<Func<T, object>>[] propertiesToUpdate)
{
Context.Set<T>().Attach(obj);
foreach (var p in propertiesToUpdate)
{
Context.Entry(obj).Property(p).IsModified = true;
}
}
And then to call, for example:
public void UpdatePasswordAndEmail(long userId, string password, string email)
{
var user = new User {UserId = userId, Password = password, Email = email};
Update(user, u => u.Password, u => u.Email);
Save();
}
public interface IRepository
{
void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}
public class Repository : DbContext, IRepository
{
public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
{
Set<T>().Attach(obj);
propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
SaveChanges();
}
}
//3
public int Update(TEntity entity)
{
dbcontext.Set<TEntity>().Attach(entity);
PropertyInfo[] props = entity.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.GetValue(entity, null) != null)
{
if (prop.GetValue(entity, null).ToString() == " ")
dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null;
dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
}
}
return dbcontext.SaveChanges();
}