【发布时间】:2011-01-17 00:40:07
【问题描述】:
我有两个 linq(到 EF4)查询,它们返回不同的结果。第一个查询包含正确的结果,但没有正确格式化/投影。
第二个查询是我想要的,但它缺少一些数据。
架构
alt text http://img220.imageshack.us/img220/9678/schema.png
查询 1
var xxxx = (from cp in _connectedClientRepository
.GetConnectedClients(new[] { "LogEntry", "LogEntry.GameFile" })
.AsExpandable()
.Where(predicate)
select cp)
.ToList();
alt text http://img231.imageshack.us/img231/6541/image2ys.png
注意属性 GameFile 。它是 not 空值。这很棒 :) 注意到 linq 查询了吗?我急切地加载LogEntry,然后急切地加载GameFile(对于每个急切加载的LogEntry)。
这就是我所追求的 -> 对于每个急切加载的 LogEntry,请急切加载 GameFile。但是这个投影结果是错误的……
好的..接下来...
查询 2
var yyy = (from cp in _connectedClientRepository
.GetConnectedClients(new[] { "LogEntry", "LogEntry.GameFile" })
.AsExpandable()
.Where(predicate)
select cp.LogEntry)
.ToList();
注意:上面的图片有错字...请注意包含关联输入的代码是正确的(即LogEntry.GameFile),而图片有错字。 p>
现在正确投影 -> 所有LogEntries 结果。但是请注意GameFile 属性现在是空的吗?我不知道为什么 :( 我认为我正确地渴望加载正确的链。所以这是正确的投影,但结果不正确。
强制存储库代码。
public IQueryable<ConnectedClient> GetConnectedClients(
string[] includeAssociations)
{
return Context.ConnectedClients
.IncludeAssociations(includeAssociations)
.AsQueryable();
}
public static class Extensions
{
public static IQueryable<T> IncludeAssociation<T>(
this IQueryable<T> source, string includeAssociation)
{
if (!string.IsNullOrEmpty(includeAssociation))
{
var objectQuery = source as ObjectQuery<T>;
if (objectQuery != null)
{
return objectQuery.Include(includeAssociation);
}
}
return source;
}
public static IQueryable<T> IncludeAssociations<T>(
this IQueryable<T> source, params string[] includeAssociations)
{
if (includeAssociations != null)
{
foreach (string association in includeAssociations)
{
source = source.IncludeAssociation(association);
}
}
return source;
}
}
更新
- 1:修复了代码示例中注意到的一些错字。
- 2:添加了存储库代码以帮助任何困惑的人。
【问题讨论】:
-
发送给GetConnectedClients的参数中不需要去掉“LogEntry”吗?
-
我的猜测:投影改变了结果的形状,所以
Include不再匹配。这行得通吗?((from cp in _connectedClientRepository.GetConnectedClients().AsExpandable().Where(predicate) select cp.LogEntry) as ObjectQuery).Include("GameFile").ToList();? -
@Lasse V. Karlsen:我试过了,但没有用。我还尝试了 LogEntry.GameFile 和 LogEntry,LogEntry.Game 文件.. 也没有工作。
-
@Craig Stuntz:有趣的一点......我怀疑的一点。我很快就会尝试..但是你有没有链接到有人详细解释这个?大家是否也注意到了这一点?
-
无非就是
Include的常用文档。重要的是,它适用于ObjectQuery<T>,而T很重要。这可能会有所帮助:blogs.msdn.com/alexj/archive/2009/06/02/…
标签: c# .net sql linq linq-to-entities