下面我创建了一个演示实体来演示我在寻找什么:
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
接口(interface)来使这个实体 self 验证。
现在正在创建新用户,我正在这样做
User u = new User();
u.Name = "Some name";
u.CreationDate = DateTime.Now
dbContext.Users.Add(u);
dbContext.SaveChanges();
我计划将 u.CreationDate=DateTime.Now;
代码转移到 User
类中。并实现一个接口(interface),该接口(interface)提供将在保存之前和验证之后执行的方法
// class structure that I am 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;
}
}
}
现在要创建一个新用户,我只需按照以下步骤操作,请注意,这次我没有添加日期属性,Class 会自动添加。
User u = new User();
u.Name = "Some name";
dbContext.Users.Add(u);
dbContext.SaveChanges();
要更新用户,UpdatedOnDate
属性将按类自动更新
User u = getUserFromSomeWhere();
u.Name = "Updated Name";
dataContext.Entry<User>(u).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
我的问题:是否有任何现有接口(interface)提供
在 Save
和 AfterValidate
之前调用的一些方法或其他一些我可能不知道的方法。
或者,如果我创建自定义界面,我怎样才能让它的方法按照我想要的顺序执行。
最佳答案
我有一个几乎相同的情况,我通过处理 SavingChanges 来管理它上下文事件。
首先,我创建了一个定义时间戳操作的接口(interface):
public interface IHasTimeStamp
{
void DoTimeStamp();
}
然后我在我的实体中实现这个接口(interface):
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 处理程序并实现它。
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();
}
}
}
}
关于c# - 在 Entity Framework 中,如何在保存之前调用实体上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677160/