在实体框架,如何保存之前调用方法对实体 [英] in Entity framework, how to call a method on Entity before saving
问题描述
下面我创建了一个演示实体来证明什么IAM寻找
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();
荫规划转向 u.CreationDate = DateTime.Now;
User类的内部代码。和实施提供了将在保存之前并验证IAM寻找$
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();
我的提问:是否有任何现有的接口,提供
有些方法被保存前,验证或其他一些方法后称为$这样做的b $ b,我可能不会知道。
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屋!