忽略从 WCF 请求返回的数据中的关系

Ignoring Relationships in Data Returned from WCF Request

我很难找到这方面的信息,但由于 entity framework 定义中的关系,基本上发送的数据太多了。我有几张表,但重要的是:应用程序和所有者。由于数据库中的外键约束,这里存在一对多(所有者)关系。 (见下文)

问题是:当我尝试 return 单个所有者对象时,所有应用程序数据也在 XML 中发送,但我不希望其中任何一个被送出去。相反,我希望能够创建一个操作,该操作能够在发送应用程序数据时不包含所有者信息(尽管这没什么大不了的)。

我想保持 FK 约束和关系,但限制 WCF 服务正在 returning 的数据,但我 运行 在这里被墙了。我需要修改什么才能使这项工作。

这是获取 Owner 对象的代码:

接口:

[OperationContract]
[WebGet(UriTemplate = "Apps/{id}/{ownernum}", BodyStyle = WebMessageBodyStyle.Bare)]
[Description("Gets specific owner information from the database using an appid and owner number")]
Owner GetOwnerInfo(string id, string ownernum);

实施(移除验证和其他多余代码):

public Owner GetOwnerInfo(string id, string ownernum)
{
     ...

    Owner owner = entities.Owners.SingleOrDefault(o => o.AppId == appId && o.OwnerNumber == ownerNumber);
    if (owner != null)
    {
        logger.Info("Owner {0} from application id {1} sent via HTTP GET", ownerNumber, appId);
        return owner;
    }
    else
    {
        logger.Warn("Cannot find owner {0} from application id {1}", ownerNumber, appId);
        throw new WebFaultException<string>(string.Format("Cannot find Owner {0} from AppId {1}", ownerNumber, appId), HttpStatusCode.NotFound);
    }

   ...
}

实际情况是您无论如何都不应该通过 WCF 服务发送 EF 对象。事实上, 大多数 的时候,由于循环引用,它们根本不会序列化(不知道你是怎么绕过那个的)。

不管怎样,真正的解决方案是创建一个 DataContract 正是 您要通过网络发送的数据,然后在该数据和您的数据之间编写一个转换函数EF 对象。

然后您的 WCF 服务发送的唯一对象是数据协定对象,并且您控制 is/isn 不发送的内容。

@BradleyDotNet 所说的是正确的,但作为快速修复,您可以急切地执行查询(通过 .ToList() 或查询结束时的类似方式)或禁用延迟加载 (context.Configuration.LazyLoadingEnabled = false;)

这个问题涉及到你在做什么:

How to exclude a related table when use Entity Framework

如果您以后需要加载相关项目,请使用db.MyEntity.Include(...):

https://msdn.microsoft.com/en-gb/data/jj574232.aspx