EntityFramework的Activerecord的Callbacks和NamedScope的版本

时间:2011-12-27 03:16:04

标签: asp.net-mvc asp.net-mvc-3 entity-framework activerecord

问题:在我的模型中,我需要在触发任何ORM事件之前使用回调来处理db实体对象。此外,我正在寻找一种方法来应用named-scope所以我不需要为每个查询提供某些条件。例如;当我在项目的dbcontext对象上使用Find时,我不需要为每次调用提及active = true。

问题:

  1. 在ASP.NET MVC(EntityFramework)中是否有类似于callbacks methods of ActiveRecord的内容?如:after_save,before_save,after_create,before_create,after_validation,before_validation等。

  2. 我应该创建一个“模型视图”来附加具有命令条件的每个查询吗?请提供示例或资源/教程。

1 个答案:

答案 0 :(得分:6)

没有。没有这样的事件/回调可用。 EF ObjectContext仅提供ObjectMaterializedSavingChanges个活动。第一个可用于在实体从数据库实现(加载)时作出反应,第二个可用于在保存更改之前处理任何事物(类似于覆盖SaveChanges方法)。

示例:

public void SavingChanges(object sender, EventArgs e)
{
    ObjectContext context = (ObjectContext)sender; 

    var entities = context.ObjectStateManager
                          .GetObjectStateEntries(EntityState.Added)
                          .Where(e => !e.IsRelationship)
                          .Select(e => e.Entity)
                          .OfType<MyEntity>();

    // Now you have all entities of type MyEntity which will be added
    // You can use similar approach for other type of entities or
    // modified entities or deleted entities                      
}

EF不提供任何类型的全局条件/命名范围。您必须始终确保查询包含所有条件。例如,您可以创建自定义扩展方法而不是默认查找使用该扩展方法,该方法将添加所有附加条件

示例:

public static MyEntity FindWithCondition(this IQueryable<MyEntity> query, int id)
{
    return query.Where(...).FirstOrDefault(e => e.Id == id);
}