【问题标题】:Using Unity.Mvc3 with HierarchicalLifetimeManager and Unit Of Work pattern no longer Lazy Loading将 Unity.Mvc3 与 HierarchicalLifetimeManager 和工作单元模式一起使用不再延迟加载
【发布时间】:2012-02-29 00:42:35
【问题描述】:

首先,我的 UoW 继承自 DbContext。

我转而使用 Unity.Mvc3 并将这一行添加到我的注册中:

Container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());

一旦我搬到这里,我对实体框架的延迟加载似乎停止了工作。这是一个例子:

public class Process
{
     public Guid Id {get;set;}
     public virtual Guid? StatusId {get;set;} //this is the FK EF uses.
     public virtual Status Status {get;set;}
}

public class Status
{
     public Guid ID {get;set;}
     public Name {get;set;}
}

//DTOs
public class ProcessDto
{
     public Guid Id {get;set;}
     public Guid? StatusId {get;set;} //this is the FK EF uses.
     public StatusDto Status {get;set;}
}

public class StatusDto
{
     public Guid ID {get;set;}
     public Name {get;set;}
}

在我们调用 Cre 之前,Satuse 被加载到上下文中

//Process Service
    public ProcessDto Create(ProcessDto dto)
    {
       var processEntity = new Process(){StatusId = dto.StatusId}
       processRepository.Add(processEntity)
       unitOfWork.Commit()
       //at this point, before using Unity.Mvc3 the Status would be proxied into the   processEntity. Moving to Unity.Mvc3 it is like Lazy Loading stopped working.
       return Mapper.Map<Process,ProcessDto>(processEntity);
    }

单步执行代码直到调用 Create 之后请求才会终止。不知道有没有人遇到过类似的情况。

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework dependency-injection entity-framework-4.1 unity-container


    【解决方案1】:

    您的 Status 属性不是虚拟的,因此实体永远不会被代理以进行延迟加载,Unity 或任何其他 IoC 容器对此没有影响。

    您还直接使用Process 构造函数 - 如果您创建 Process 实例,则它不能被代理并且延迟加载无法工作。您必须在 DbSet&lt;Process&gt; 上使用 Create 工厂方法来获取代理实体。

    【讨论】:

    • 我没有在这个例子中加入虚拟,但我可以向你保证,它们实际上是在我的模型中设置的。我会更新我的例子。关于您对 Process 构造函数的评论,就像我在上面所说的那样,当我回到使用 Microsoft Unity 解析器并删除 Unity.MVC3 版本时,状态实际上正在出现。
    • processEntity 工作时是什么类型(真正的运行时类型)?
    • 它是一个流程实体类型。和上面一样。你在那里看到的一切都和我的设置一样。唯一的区别是使用 Unity.MVC3 解析器。就像 UoW 在某个时候被抛弃一样。
    • 好的。我明白为什么它现在起作用了。我错过了这一点:在我们调用 Create 之前,Satuses 已在上下文中加载因此一直没有延迟加载,因为数据已加载。
    • 在我调用 create 之前它们是上下文的一部分,是的。所以,在我在 Create 方法中提交之后,状态的 FK 被 EF 拾取以将它们加载到 Process 实体上。但是,仅当我使用“开箱即用”的 Unity 解析器时。真的很奇怪。
    猜你喜欢
    • 2017-11-17
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2018-11-22
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多