摘要
在使用EF的时候,由于表字段较多,所以在更新的时候,想要只更新变化的字段,有没有办法呢?
解决办法
代码片段
public async Task<int> UpdateAsync(T entity, List<string> fieldNames)
{
using (var context = new RetailContext())
{ if (fieldNames != null && fieldNames.Count > )
{
context.Set<T>().Attach(entity);
foreach (var item in fieldNames)
{
context.Entry<T>(entity).Property(item).IsModified = true;
}
}
else
{
context.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
} return await context.SaveChangesAsync();
}
}
将变化的字段名称放在集合中,并修改其是否变化的状态。
public async Task<int> UpdateAsync(T entity, Dictionary<string, object> dic)
{
try
{ if (dic != null)
{
SetValue<T>(dic, entity);
return await _baseData.UpdateAsync(entity, dic.Keys.ToList());
}
else
{
return await _baseData.UpdateAsync(entity, null);
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 通过反射设置值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dic"></param>
/// <param name="entity"></param>
public static void SetValue<T>(Dictionary<string, object> dic, T entity) where T : class ,new()
{
Type t = entity.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (var item in properties)
{
foreach (var key in dic.Keys)
{
if (key.ToLower() == item.Name.ToLower())
{
switch (item.PropertyType.ToString())
{
case "System.Int32":
item.SetValue(entity, Convert.ToInt32(dic[key]), null);
break;
case "System.Boolean":
item.SetValue(entity, Convert.ToBoolean(dic[key]), null);
break;
case "System.String":
item.SetValue(entity, Convert.ToString(dic[key]), null);
break;
case "System.Decimal":
item.SetValue(entity, Convert.ToDecimal(dic[key]), null);
break;
case "System.DateTime":
item.SetValue(entity, Convert.ToDateTime(dic[key]), null);
break;
case "System.Guid":
Guid g = dic[key] == null ? new Guid() : new Guid(dic[key].ToString());
item.SetValue(entity, g, null);
break;
default:
item.SetValue(entity, dic[key], null);
break;
} }
}
}
}
通过反射的方式对变化的字段进行赋值。字段中保存变化的字段名称与值。