假设更新学生实体
public class Student{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Gender { get; set; } //True=>male, False=>female
}
数据库上下文
public class StudentDbContext : DbContext{
public DbSet<Student> Students { get; set; }
}
对应通用的Repository
private readonly StudentDbContext _db;
public int UpdateByProperties(List<Student> students, params Expression<Func<Student, dynamic>>[] properties)
{
students.ForEach(student =>
{
foreach (var propety in properties)
{
_db.Entry(student).Property(property).IsModified = true;
}
});
return _db.SaveChanges();
}
表达式Expression
中传入Student
对象,返回Student
属性,应当使用Func
。又因为属性类型是可变的,所以这里返回类型使用dynamic
,综上Func<Student, dynamic>
。
使用示例
var stu = _db.Students.FirstOrDefault(s => s.ID == 1);
stu.Name = "New";
stu.Age++;
UpdateByProperties(stu, s => s.Name, s => s.Age);