如何阻止EF加载整个对象图 [英] How to stop EF from loading entire object graph

查看:82
本文介绍了如何阻止EF加载整个对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个EF模型,我已经将延迟加载设置为true。我做这个查询:

  public static WorkflowStatus Get(int id)
{
WorkflowStatus status;
使用(var db = new WorkflowDb())
{
status = db.WorkflowStatuses
.Include(CurrentMappings)
.Include(CurrentMappings.NextWorkflowStatus )
.Include(NextMappings)
.Include(NextMappings.CurrentWorkflowStatus)
.Include(WorkQueueWorkflowStatusMaps)
.Include(WorkQueueWorkflowStatusMaps.WorkQueue)
.FirstOrDefault(x => x.Id == id);
}
返回状态;
}

在我得到状态后,不仅仅是填充了这些东西。例如,每个WorkQueueWorkflowStatusMap都有一个WorkQueue和WorkQueue有一个WorkQueueWorkflowStatusMaps的集合 - 所以有无限量的来回加载。我该如何阻止?当我通过另一层的WCF服务返回时,会引发异常,因为这样。

解决方案


如何阻止EF加载整个对象图?


所有这些包括你告诉EF加载整个对象图。每个包括说:加载这个关系。


所以有无限量的来回加载


否。实体只加载一次。您看到的是循环引用,它包含在您的模型中。如果您的 WorkQueueWorkflowStatusMap 具有 WorkQueue 导航属性,同时 WorkQueue WorkQueueWorkflowStatusMap 导航属性比您建模的循环引用绝对正确,直到您尝试序列化您的实体= WCF中的问题。在这种情况下,您必须通知序列化程序循环引用



如果你想使用序列化和WCF,你应该遵循@ Eranga删除的答案 - 关闭延迟加载和代理创建。


I have an EF model where I have set lazy loading to true. I do this query:

public static WorkflowStatus Get(int id)
{
    WorkflowStatus status;
    using (var db = new WorkflowDb())
    {
        status = db.WorkflowStatuses
            .Include("CurrentMappings")
            .Include("CurrentMappings.NextWorkflowStatus")
            .Include("NextMappings")
            .Include("NextMappings.CurrentWorkflowStatus")
            .Include("WorkQueueWorkflowStatusMaps")
            .Include("WorkQueueWorkflowStatusMaps.WorkQueue")
            .FirstOrDefault(x => x.Id == id);
    }
    return status;
}

After I get the status back there is more than just those things being populated. For example each WorkQueueWorkflowStatusMap has a WorkQueue and WorkQueue has a collection of WorkQueueWorkflowStatusMaps - so there is an infinite amount of back and forth being loaded. How do I get that to stop? When I return this through a WCF service in another layer it throws an exception because of this.

解决方案

How to stop EF from loading entire object graph?

By all those includes you told EF to load whole object graph. Every include says: load this relation as well.

so there is an infinite amount of back and forth being loaded

No. Entities are loaded only once. What you see is circular reference which is included in your model. If your WorkQueueWorkflowStatusMap has WorkQueue navigation property and in the same time WorkQueue has WorkQueueWorkflowStatusMap navigation property than you modeled circular reference which is absolutely correct until you try to serialize your entity = problem in WCF. In such case you must inform serializer that circular references are used.

If you want to use serialization and WCF you should follow @Eranga's deleted answer - turn off lazy loading and proxy creation.

这篇关于如何阻止EF加载整个对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆