【问题标题】:Using IQueryable<T> with LINQ join tables将 IQueryable<T> 与 LINQ 连接表一起使用
【发布时间】:2017-09-18 21:53:22
【问题描述】:

我有一个IQueryable&lt;T&gt; 类型的方法,这是它的实现:

 public IQueryable<T> Get()
 {
     return db.Set<T>();
 }

我必须编写 LINQ 查询来连接两个表(左连接)。是 Identtiy 表 Users 和我的自定义表 PersonalInformation 扩展了用户注册字段,现在我想在我的 LINQ 查询中调用这个方法,这很好。这是我的 Linq:

IRepository<PersonalInformation> personRepository;
IRepository<ApplicationUser> usersRepository;
var query = personRepository.Get();
var test = usersRepository.Get()
                          .GroupJoin(query,
                                     n => n.Id,
                                     m => m.UserId,
                                     (n, ms) => new { n, ms = ms.DefaultIfEmpty() })
                          .SelectMany(z => z.ms.Select(m => new PersonalInfoModel
                          {
                              Name = m.Name,
                              LastName = m.LastName,
                              Email = z.n.Email
                          }));

但是我有一个错误 var test = usersRepository.Get() - System.NotSupportedException。因此,从 personRepository 中获取的方法调用良好,但 usersRepository 方法返回 null。我哪里做错了??谢谢

【问题讨论】:

  • GetIRepository 的成员吗?
  • @NetMage 是的,它是接口 IRepository : IDisposable where T : class 并且有 IQueryable Get();我在 linq 中有一个不同的上下文错误
  • 所以usersRepository的真实类型有可能没有实现IRepositoryGet操作。虽然我不喜欢它,但有些类部分实现了接口。 personRepositoryusersRepository的真实类型是什么?
  • @NetMage 对不起,我不明白它显示(字段)IRepository HomeControloller.personRepository。接下来我还在 HomeContoller 的构造函数中创建: personRepository = new MainRepository();和 usersRepository = new MainRepository();
  • @NetMage 我想我知道哪里出错了。在我实现方法 get 的 MainRepository 中,我使用 return db.Set();其中 db 是 ApplicationDbContext ,但这很奇怪,因为 ApplicationDbContext 是身份上下文,我不明白为什么会出错

标签: asp.net-mvc linq iqueryable


【解决方案1】:

您可能在组合来自两个不同数据库上下文的查询时遇到错误。您的自定义 PersonalInformation 可能在自定义 DBContext 中,而 UsersIdentityDBContext 中。见this related question。您可以:

将所有表格移动到同一上下文中。

  • 避免将来在这些表之间产生混淆
  • 如果您最终在上下文中有大量关联,则效率会更高。
  • 一个更复杂的解决方案只是为了让这个示例正常工作。

单独查询您的表并在内存中合并。

  • 如果您拥有大量用户,则可扩展性较差。
  • These operators will cause EF to return the results so you can process in memory.

    var people = personRepository.Get().ToList();
    var users = usersRepository.Get().ToList();
    var infoModels = users.GroupJoin(people,
                                     u => u.Id,
                                     p => p.UserId,
                                     (u, mp) => new { n, ms = ms.DefaultIfEmpty() })
                          .SelectMany(z => z.ms.Select(m => new PersonalInfoModel
                          {
                              Name = m.Name,
                              LastName = m.LastName,
                              Email = z.n.Email
                          }));
    

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多