首页 > 代码库 > 反射做字段更新日志

反射做字段更新日志

思路给类的属性加特性标签,重写savechanges方法,获取当前entry反射查看是否存在标记为通知修改做日志的属性。

 [Table("Student")]    public partial class Student    {        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public int id { get; set; }        [StringLength(50)]        [Notice]        public string Name { get; set; }        [Notice]        public int Age { get; set; }    }    public class NoticeAttribute : Attribute    { }
  public override int SaveChanges()        {            ObjectContext context = (this as IObjectContextAdapter).ObjectContext;            foreach (ObjectStateEntry entry in context.ObjectStateManager                      .GetObjectStateEntries(EntityState.Added | EntityState.Modified))            {                var model = entry.Entity;                //获取类型方式1                var t1 = model.GetType();                //获取类型方式2                //var t2 = ObjectContext.GetObjectType(t1);                //获取类型方式3                //var ass = Assembly.GetExecutingAssembly();                //var name = ass.GetName();                //var type=ass.GetType(name.Name+ "."+t1.Name);                //获取当前实体所有标记为修改的属性                var mp = entry.GetModifiedProperties();                //获取类的所有属性                             var pro = t1.GetProperties();                //日志信息                StringBuilder log = new StringBuilder();                log.Append("当前用户\t").Append(t1.Name).Append("\t属性\t");                foreach (var p in pro)                {                    //判断类的属性是否有通知修改的特性                    var atr = p.GetCustomAttribute(typeof(NoticeAttribute));                    //如果属性有标记修改的特性,并且当前实体此属性标记为modified                    if (atr != null && mp.Contains(p.Name))                    {                        //var value = http://www.mamicode.com/entry.CurrentValues;>//var data = http://www.mamicode.com/entry.CurrentValues.DataRecordInfo.FieldMetadata.FirstOrDefault(f=>f.FieldType.Name==p.Name);>//获取当前属性值                        var result = p.GetValue(model);                        log.Append(p.Name).Append("\t修改为\t").Append(result).Append("\t");                    }                }                Console.WriteLine(log.ToString());            }            return base.SaveChanges();        }
  static void Main(string[] args)        {            Model1 db = new Model1();            var student= db.Students.FirstOrDefault();            student.Name = "sfdsfsfsf";            student.Age = 18;            DbEntityEntry<Student> entry = db.Entry<Student>(student);            entry.State = System.Data.Entity.EntityState.Unchanged;            entry.Property("Name").IsModified = true;            entry.Property("Age").IsModified = true;            db.SaveChanges();            Console.ReadKey();        }

技术分享

 

反射做字段更新日志