访问实体框架包含方法

时间:2015-01-21 12:05:55

标签: c# linq entity-framework

我尝试使用QueryResultCachemotioned here访问实体框架的Include方法。它是一篇非常受欢迎的文章,很多查询缓存库都在使用它。 当我尝试表达式时:

var exp1 = context.Products.Include(x => x.Tags)
                   .Where(x => x.Tags.Any(y => y.Name.Contains("Test")))
                   .Select(x => new {x.ProductId}).Expression;

用它来生成这个字符串:

value(System.Data.Entity.Core.Objects.ObjectQuery`1
[EfSecondLevelCaching.Test.Models.Product]).MergeAs(AppendOnly).IncludeSpan
(value(System.Data.Entity.Core.Objects.Span))
.Where(x => x.Tags.Any(y => y.Name.Contains("Test")))
.Select(x => new <>f__AnonymousType5`1(ProductId = x.ProductId))

如您所见,结果不包含Include方法的参数(x =&gt; x.Tags)。因此,网络上的大多数linq缓存库都无法为EF查询创建有效的唯一查询密钥。我该如何解决这个问题?

编辑:

如果我删除了select方法,它将产生:

value(System.Data.Entity.Core.Objects.ObjectQuery`1
[EfSecondLevelCaching.Test.Models.Product])
    .MergeAs(AppendOnly)
    .IncludeSpan(value(System.Data.Entity.Core.Objects.Span))
    .Where(x => x.Tags.Any(y => y.Name.Contains("Test")))

所以Include(x=>x.Tags)Include(x=>x.Users)之间没有区别。

1 个答案:

答案 0 :(得分:0)

查询将仅返回Select表达式中的内容。在这种情况下,Select(x => new {x.ProductId})表示只返回一个字段ProductId

如果您Include包含ProductsTags会产生影响,但如果您只有ProductId,则会有所不同。

有关预先加载的更多信息,请参阅this MSDN articleInclude确保预先加载)

相关问题