gpt4 book ai didi

c# - 有人可以解释为什么这两个 linq 查询返回不同的结果吗?

转载 作者:可可西里 更新时间:2023-11-01 08:49:32 25 4
gpt4 key购买 nike

我有两个 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 。它为空。这很棒 :) 注意到 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();

alt text

注意:上面的图片有错字...请注意包含关联类型的代码是正确的(即 LogEntry.GameFile),而图片有打错了。

现在更正投影 -> 所有 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:添加了存储库代码以帮助任何感到困惑的人。

最佳答案

我怀疑 Craig Stuntz 的建议可能会奏效,但如果没有,以下肯定会奏效:

 var xxxx =_connectedClientRepository
.GetConnectedClients(new[] { "LogEntry", "LogEntry.GameFile" })
.AsExpandable()
.Where(predicate)
.ToList() // execute query
.Select(cp => cp.LogEntry); // use linq-to-objects to project the result

关于c# - 有人可以解释为什么这两个 linq 查询返回不同的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com