在实体框架中,如何在保存之前调用实体的方法 [英] in Entity framework, how to call a method on Entity before saving
问题描述
下面我创建了一个演示实体来演示我在寻找什么
Below i have created a demo entity to demonstrate what iam looking for
public class User : IValidatableObject
{
public string Name{get;set;}
[Required]
public DateTime CreationDate{get;set;}
public DateTime UpdatedOnDate{get;set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(Name="abc")
{
yield return new ValidationResult("please choose any other name then abc", new[] { "Name" });
}
}
}
我正在执行 IValidatableObject
界面来使这个实体SelfValidating。
I am implementing IValidatableObject
interface to make this entity SelfValidating.
现在正在创建新的用户iam这样做
Now currently to create new User iam doing this
User u= new User();
u.Name="Some name";
u.CreationDate=DateTime.Now
dbContext.Users.Add(u);
dbContext.SaveChanges();
Iam计划转移 u.CreationDate = DateTime.Now;
用户类内的代码。并实现一个接口,提供一个方法,该方法将在保存之前和验证后执行
Iam planning to shift u.CreationDate=DateTime.Now;
code inside User class. And implement an interface that provides a method which will be executed before saving and after validating
// class structure that iam looking for
public class User : IValidatableObject,IMyCustomInterFace
{
//rest codes as above class
public void MyMethod(Whatever)
{
//this method gets called after Validate() and before save
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
{
//add creation date_time
this.CreationDate=DateTime.Now;
//SET MORE DEFAULTS
}
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
{
//update Updation time
this.UpdatedOnDate=DateTime.Now;
}
}
}
现在创建一个新用户我只需要做如下,
注意我没有添加日期属性这一次,类自动执行
now to create a new user i just have to do as below, note i didnt added date property this time, Class does that automatically
User u= new User();
u.Name="Some name";
dbContext.Users.Add(u);
dbContext.SaveChanges();
要更新用户, UpdatedOnDate
属性将根据课程自动更新
To update user, UpdatedOnDate
property will be automatically updated by class
User u= getUserFromSomeWhere();
u.Name="Updated Name";
dataContext.Entry<User>(u).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
我的问题:是否有任何现有的界面提供
一些在保存和验证之后调用的方法,或者其他方式
执行此操作,我可能不知道。
My Question: is there any existing interface that provides some method that gets called before Save and After Validate or some other ways of doing this, that i may not be knowing.
或者如果我创建我的自定义接口我如何使其方法按照我正在寻找的顺序执行
Or if I create my custom interface how can i make its method to get executed in the order i am looking for
推荐答案
我有一个几乎相同的情况,我通过在上下文中处理 SavingChanges 事件来管理它。
I have an almost identical situation and I manage it by handling the SavingChanges event on the context.
首先我创建一个定义时间戳操作的界面:
First I create an interface that defines the timestamping operations:
public interface IHasTimeStamp
{
void DoTimeStamp();
}
然后我在我的实体中实现这个界面:
Then I implement this interface in my entities:
Public class User : IHasTimeStamp
(
public void DoTimeStamp()
{
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
{
//add creation date_time
this.CreationDate=DateTime.Now;
}
if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
{
//update Updation time
this.UpdatedOnDate=DateTime.Now;
}
}
}
最后一步是注册SavingChanges处理程序并实现它。
The final step is to register the SavingChanges handler and implement it.
public partial class MyEntities
{
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges
+= new EventHandler(context_SavingChanges);
}
// SavingChanges event handler.
private static void context_SavingChanges(object sender, EventArgs e)
{
// Validate the state of each entity in the context
// before SaveChanges can succeed.
foreach (ObjectStateEntry entry in
((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship && (entry.Entity is IHasTimeStamp))
{
(entry.Entity as IHasTimeStamp).DoTimeStamp();
}
}
}
}
这篇关于在实体框架中,如何在保存之前调用实体的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!