问题描述
我开始通过创建一些模型是这样的:
I started by creating some models like this:
public abstract class EditableBase
{
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public int CreatedBy { get; set; }
public int ModifiedBy { get; set; }
}
public class Project : EditableBase
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
}
和我用这个线的时候,应用程序启动:
And I use this line when the app starts:
Database.SetInitializer<ModelContext>(
new DropCreateDatabaseIfModelChanges<ModelContext>());
称为项目与上面提到的列的所有属性创建的表...这到底是什么我想要的。
A table called Projects is created with all the properties mentioned above as columns... this is exactly what I wanted.
不过,现在我需要填充一些默认值时,我发出的SaveChanges()上的DbContext。当我救我需要更新相应的值ModifiedOn和ModifiedBy属性。
However, now I need populate some default values when I issue a SaveChanges() on DbContext. When I save I need to update the ModifiedOn and ModifiedBy properties with the appropriate values.
通常我至少会做在数据库端的DateTime值(一个触发器或存储过程),但是这显然不是一个不错的选择,因为该数据库将随时丢弃类的变化。因为我第一次做的代码我没有,我可以调整性质的模型设计。
Normally I would at least do the DateTime values on the database side (either a trigger or a stored procedure) however this is obviously not an option here since the database will be dropped anytime a class changes. And since I did code first I do not have a model designer that I can tweak the properties on.
我想什么做的是在EditableBase类添加一个方法当调用SaveChanges()被执行,从而使所有参与一个地方逻辑被调用。是否有可能做到这一点?什么是实现我目标的最佳方式是什么?
What I would like to do is add a method in the EditableBase class that gets called when the SaveChanges() is executed, thus keeping all the logic involved in one place. Is it possible to do this? What is the best way to achieve my goal?
推荐答案
覆盖的SaveChanges
在派生的DbContext
:
public override int SaveChanges()
{
foreach(var entry in ChangeTracker.Entries<EditableBase>())
{
var entity = entry.Entity;
if (entry.State == EntityState.Added)
{
entity.CreatedOn = ...;
entity.CreatedBy = ...;
}
else if (entry.State == EntityState.Modified)
{
entity.ModifiedOn = ...;
entity.ModifiedBy = ...;
}
}
return base.SaveChanges();
}
我只是不知道,如果通用条目
becasue它实际上没有映射为基础的实体将直接与您的基本类型的工作。也有非一般的版本,所以你可以把它改写到更复杂的LINQ查询或测试循环中的每个条目的实体类型。
I'm only not sure if generic Entries
will work directly with your base type becasue it is not actually mapped as base entity. There is also non generic version so you can rewrite it to more complex linq query or test each entry's entity type in loop.
这篇关于我如何使用代码首先EF4.1保存时添加默认值的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!