假设更新学生实体
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);
本文介绍了一个基于C#的通用方法,用于更新数据库中学生实体的特定属性,通过使用表达式树和Lambda表达式来动态修改属性值,此方法提高了代码的复用性和维护性。
2万+

被折叠的 条评论
为什么被折叠?



