实体框架5.多个包含。这可能吗? [英] Entity Framework 5. Multiple Include. Is this possible?

查看:46
本文介绍了实体框架5.多个包含。这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的存储库中创建一个多重包含方法,以按以下方式使用:

I am trying to create a multiple include method in my repository to use as follows:

repository.Include<Post>(x => x.Images, x => x.Tags).First(x => x.Id == 1)

我尝试了以下操作:

public IQueryable<T> Include<T>(params Expression<Func<T, Object>>[] paths) where T : class {
  return paths.Aggregate(_context.Set<T>(), (x, path) => x.Include(path));
} // Include

但是我得到了错误:

不能将类型'System.Linq.IQueryable'隐式转换为'System.Data.Entity.DbSet'。

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Entity.DbSet'.

请注意,原始包含如下:

Note that the original include is the following:

公共静态IQueryable Include(
此IQueryable源,
Expression>路径
)其中T:class;

public static IQueryable Include( this IQueryable source, Expression> path ) where T : class;

我可以在不将存储库方法转换为静态的情况下进行此工作吗?

Can I make this work without turning my repository method into static?

谢谢,

Miguel

推荐答案

如果您真的想创建自己的 .include 非扩展方法,允许一次调用多个路径,内部转换为已经提供的 .Include 方法,您可以执行类似操作

If you really want to create your own .Include non-extension method that allows for multiple paths in one call, internally translating to the already provided .Include method, you can do something like

public IQueryable<T> Include<T>(params Expression<Func<T, object>>[] paths)
    where T : class
{
    IQueryable<T> query = _context.Set<T>();
    foreach (var path in paths)
        query = query.Include(path);
    return query;
}

这与您已经拥有的内容非常接近,但是避免了<您遇到的code> Enumerable.Aggregate :如果替换 IQueryable< T> ;,也会遇到同样的问题。查询在我的版本中带有 var查询

This is pretty close to what you have already, but avoids the pitfall with Enumerable.Aggregate that you encountered: you'd have the same problem if you replace IQueryable<T> query with var query in my version.

请注意,使用许多 .include 可能会损害性能。如果您遇到这种情况,可以将其重写以使用多个查询,可以在一个事务中一个接一个地运行它们。

Note that using many .Include may harm performance. If it does in your situation, you can rewrite it to use multiple queries, which you can run one after the other in a transaction.

个人,您可以将其称为已经在任何 IQueryable上提供了 .Include 扩展方法(使用System.Data.Entity; ,我将其写为:

Personally, as you can call the already provided .Include extension method (using System.Data.Entity;) on any IQueryable, I'd just write it as:

repository.Posts.Include(x => x.Images).Include(x => x.Tags).First(x => x.Id == 1)

这篇关于实体框架5.多个包含。这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆