[英]Entity Framework Core Lambda Expression join 4 tables and filter with where
我有六个表,如下所示。 我正在尝试根据Application_name
、 Environment_name
和Status
获取数据。
状态表:
Id, Name
申请表:
Id, Name
服务器表:
Id, ServerName, Status
环境表:
Id, Name
资源组表:
Id, Name, Application_Id, Environment_Id
服务器资源组:
Id, Server_Id, Resource_Id
我想要做的是加入所有 require 表并使用 where 来过滤数据Application_name
、 Environment_name
和Status
这是我构建的查询,它通过过滤Application_name
返回所有数据,但我无法通过添加Environment_name
和Status
额外过滤器来满足上述要求:(
所以下面是返回带有Application_name
所有数据的查询
public IEnumerable<ResourceGroup> GetAllServersByApplication(string application_name, string environment_name, string status)
{
var query = _context.ResourceGroup
.Include(a => a.Application)
.Include(t => t.Type)
.Include(e => e.ServersGroup).ThenInclude(e => e.Environment)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server).ThenInclude(s => s.Status)
.Where(a => a.Application.Name == application_name)
.ToList();
return query;
}
这是我尝试编写的查询,它将基于所有三个过滤器进行过滤:
public IEnumerable<ResourceGroup> GetAllServersByApplication(string application_name, string environment_name, string status)
{
var query = _context.ResourceGroup
.Include(a => a.Application)
.Include(t => t.Type)
.Include(e => e.ServersGroup).ThenInclude(e => e.Environment)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server).ThenInclude(s => s.Status)
.Where(a => a.Application.Name == application_name)
.Select(e => e.ServersGroup.Where(s => s.Environment.Name == environment_name && s.Server.Status.Name == status)
.ToList();
return query;
}
有没有更简单的方法来编写 lambda 查询然后我想要做什么?
任何帮助都非常感谢。 :)
谢谢,
射线
出现错误是因为您现在正在返回与您的方法签名不同的ServersGroup
集合。 这是因为您添加了 Select 子句并从ResourceGroup
选择了属性ServersGroup
。 过滤应该发生在Where
子句中。 我更新了下面的代码,并将Select
中的过滤器移动到Where
,也将包含的 where 更改为Any
作为 Where 期望布尔子句。
如果您打算只在您的ResourceGroup
包含某些ServersGroup
,那么您应该在连接或外部连接语句中过滤掉那些。
此外,您可能不需要到处都包含。 包含用于急切加载,以确保数据库只需要一次往返即可获取关联关系。 如果您不打算访问所有这些相关属性,则不要包含它们。
我确实假设您的关系在流畅的映射文件中或使用模型上的属性正确映射。
public IEnumerable<ResourceGroup> GetAllServersByApplication(string application_name, string environment_name, string status)
{
var query = _context.ResourceGroup
.Include(a => a.Application)
.Include(t => t.Type)
.Include(e => e.ServersGroup).ThenInclude(e => e.Environment)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server)
.Include(s => s.ServersGroup).ThenInclude(s => s.Server).ThenInclude(s => s.Status)
.Where(a => a.Application.Name == application_name && a.ServersGroup.Any(s => s.Environment.Name == environment_name && s.Server.Status.Name == status))
.ToList();
return query;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.