1.更新单个字段
/// <summary>
/// 更新字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="conditions">where 筛选对象</param>
/// <param name="updateLamda">更新字段</param>
/// <returns></returns>
public IEnumerable<T> Update<T>( Expression<Func<T, bool>> conditions,Func<T, dynamic> updateLamda) where T : ModelBase
{
List<T> setList;
if (conditions!=null)
{
setList= this.Set<T>().Where(conditions).ToList();
}
else
{
setList = this.Set<T>().ToList();
}
foreach (var item in setList)
{
SetValue<T>(item, updateLamda);
this.Entry<T>(item).State = EntityState.Modified;
}
this.SaveChanges();
return setList;
} public dynamic SetValue<T>(T entity, Func<T, dynamic> expr)
{
return expr(entity);
}
更新单个字段
action中的使用:
public ActionResult Edit()
{
using (ActivityDbContext dbContext = new ActivityDbContext())
{
dbContext.Update<Order>(u => u.ID==1,u =>u.UserName= u.OrderNumber.Replace("1", "xx"));
//第一个lambda表达式是用来筛选的,第二个则是进行替换的,在方法编写里面,用了dynamic动态对象,因为没办法确定改了哪个属性,只不过暂时只能改一个,改多个还不会(-_-)
} return View();
}
2.lambda修改对象的属性
public dynamic SetValue<T>(T entity, Func<T, dynamic> expr)
{
return expr(entity);
}
添加对象自身方法
public static class UpdateObject
{
public static dynamic SetValue2<T>(this T obj, Func<T, dynamic> expr)
{
return expr(obj);
}
public static dynamic SetValue2<T>(this T obj, List<Func<T, dynamic>> expr)
{
foreach (var item in expr)
{
item(obj);
}
return obj;
} }
class Program
{
static void Main(string[] args)
{ #region 修改对象属性方法
GetProperty p = new GetProperty() { Name1 = "" };
//SetValue<GetProperty>(p, u => u.Name1 = "2");
Console.WriteLine(p.Name1);
//p.SetValue2<GetProperty>(u => u.Name2 = u.Name2 + 1 + 2);
p.SetValue2<GetProperty>(new List<Func<GetProperty, dynamic>>() { new Func<GetProperty, dynamic>(u => u.Name2 = u.Name2 + ), new Func<GetProperty, dynamic>(u => u.Name3 = u.Name3 + ) });
Console.WriteLine(p.Name2);
Console.WriteLine(p.Name3);
#endregion
Console.ReadKey();
} public static string GetPropertyName<T>(Expression<Func<T,string>> expr)
{
var name = ((MemberExpression)expr.Body).Member.Name;
return name;
} public static dynamic SetValue<T>(T entity, Func<T, dynamic> expr)
{
return expr(entity);
} public static dynamic SetValue<T>(T entity,List< Func<T, dynamic>> expr)
{
foreach (var item in expr)
{
item(entity);
}
return entity;
} } public static class UpdateObject
{
public static dynamic SetValue2<T>(this T obj, Func<T, dynamic> expr)
{
return expr(obj);
}
public static dynamic SetValue2<T>(this T obj, List<Func<T, dynamic>> expr)
{
foreach (var item in expr)
{
item(obj);
}
return obj;
} } public class GetProperty{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
}
控制台-修改对象属性