如何在插入或更新之前调用方法 [英] How to call a method before insert or update

查看:75
本文介绍了如何在插入或更新之前调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Entity Framework的项目,每个表或实体都有相同的两列created_date和modified_date,我想在插入实体对象之前填充这两个属性或更新它。



怎么办?

i have a project used Entity Framework, every table or entity has a same two columns "created_date and modified_date", i want to fill both properties before inserting entity object or update it.

how can do it?

推荐答案

试试这样..







Try like this..



public void Create<T>(T obj)
   {
       var created_date = typeof(T).GetProperty("created_date");
       var modified_date = typeof(T).GetProperty("modified_date");
       created_date.SetValue(obj, DateTime.Now, null); // it will saved with current time
       modified_date.SetValue(obj, null, null); // it will be null on first time
   }
   public void Modify<T>(T obj)
   {
       var created_date = typeof(T).GetProperty("created_date");
       var modified_date = typeof(T).GetProperty("modified_date");
       created_date.SetValue(obj, created_date.GetValue(obj, null), null); // it will saved with created time
       modified_date.SetValue(obj, DateTime.Now, null); // it will saved with current time
   }


每当您在DB中第一次插入该值时,它应该使用代码或直接DB中的默认日期时间值进入创建日期列。在插入之前更新时不需要这样做。如需更多参考,请查看此示例。



http://stackoverflow.com/questions/6677160/in-entity-framework-how-to-call-a-method-on-entity-before -saving [ ^ ]
Whenever you 'insert' the value in DB first time it should go in created date column with the default Datetime value either from code or from direct DB. Do same when update no need to do this before insert. For more reference you can check this example.

http://stackoverflow.com/questions/6677160/in-entity-framework-how-to-call-a-method-on-entity-before-saving[^]


这篇关于如何在插入或更新之前调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆