【问题标题】:Loading a Child (Navigation Property) Entity not working加载子(导航属性)实体不起作用
【发布时间】:2010-08-13 00:52:01
【问题描述】:

我在这个问题上遇到了非常艰难的时期。我有一个名为 Attachment 的导航属性,它是名为 ContentChannel 的实体的一部分。 ContentChannel 与 KioskType 是多对一关系。

在我的域服务扩展类中,我有以下查询:

public IQueryable<ContentChannel> GetContentChannelFromKioskType( long kioskTypeID )
{
    var returnSet = (from cc in ObjectContext.ContentChannels.Include( "Attachment" )
                   join pcc in ObjectContext.PublishedContentChannels on cc.ContentChannelID equals pcc.ContentChannelID
                        where pcc.KioskTypeID == kioskTypeID
                        select cc);
    return returnSet;
}

这对于返回 ContentChannels 列表非常有效。但是每个 ContentChannel 中的 Attachment 都是空的。

我已经在 ContentChannel 元数据类中的附件属性上尝试了 [Include],与上述查询中的 ContentChannels.Include("Attachment") 结合使用 - 不走运,附件始终为空。

我挖了更多,然后找到了一些可以显式加载我的子项的东西:

ObjectContext.LoadProperty( returnSet, "Attachment" );

但这会产生以下错误:

无法为分离的实体显式加载属性。使用 NoTracking 合并选项加载的对象始终是分离的。

是不是因为我正在做一个连接,所以事情很不稳定并且包含不起作用?我需要做什么?当我获得 ContentChannel 时,需要加载这些附件!

有什么想法吗?

【问题讨论】:

    标签: silverlight entity-framework silverlight-4.0 entity-framework-4


    【解决方案1】:

    通过在您的查询中包含join,您改变了查询的形状,在Include 之后。所以Include is discardedBut you don't need the join:

    public IQueryable<ContentChannel> GetContentChannelFromKioskType( long kioskTypeID )
    {
        var returnSet = (from cc in ObjectContext.ContentChannels.Include( "Attachment" )
                         where cc.PublishedContentChannels.Any(pcc => pcc.KioskTypeID == kioskTypeID)
                         select cc);
        return returnSet;
    }
    

    【讨论】:

    • 这不会编译。 cc 里面确实有 ContentChannel,它有 PublishedContentChannels- 我无法在 PCC 中访问 KioskTypeID。不过文章不错!
    • 好吧,我不得不猜测关联/导航名称和多重性。我会用你添加的信息更新答案
    • 这有效:(来自 cc in ObjectContext.ContentChannels.Include("Attachment" ) from pcc in cc.PublishedContentChannels.Where(e => e.KioskTypeID == kioskTypeID) select cc)但我仍然需要 Where 语句和 from;您使用了 where 然后 any。这也正确吗?
    • 对吗?可能是。这不一样。您的版本每个 PCC 返回 1 行(因此,如果 CC 有 2 个 PCC,您将获得 2 个具有相同 CC 的 CC 行)。我的每个 CC 返回 1 个。选择适合您的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多