【发布时间】:2016-10-15 02:53:27
【问题描述】:
我对 .NET 的 Lambda 表达式和尝试使用 lambda 表达式从 SQL 获取数据的经验较少。通过以下查询,我可以取回数据,但不想使用include 从其他表中获取所有属性。
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;
}
让我们以下面的包含语句为例。
.Include(s => s.ServersGroup).ThenInclude(s => s.Server)
从s.Server,我只想选择Id,ServerName,Status, and IPAddress。这些是我作为模型创建的 Servers 类的属性。
排除所有包含并仅显示我感兴趣的属性的简单方法是什么?
这是我的表格及其属性:
状态表:
Id, Name
应用程序表:
Id, Name
服务器表:
Id, ServerName, Status
环境表:
Id, Name
资源组表:
Id, Name, Application_Id, Environment_Id
ServersResourceGroup 表:
Id, Server_Id, Resource_Id
更新 1:
var query = _context.ResourceGroup
.SelectMany(rg => rg.ServersGroup
.Select(sg => new
{
ResourceName = rg.Name,
ApplicationName = rg.Application.Name,
ServerName = sg.Server.ServerName,
EnvironmentName = sg.Environment.Name,
Status = sg.Server.Status.Name
})).Where(a => a.ApplicationName == application_name && a.EnvironmentName == environment_name && a.Status == status).ToList();
return query;
更新 2:
这里是查询语法:
var query = from rg in _context.ResourceGroup
let app = rg.Application
from sg in rg.ServersGroup
let env = sg.Environment
let srv = sg.Server
let stat = srv.Status
where app.Name == application_name
&& rg.ServersGroup.Any(s => s.Environment.Name == environment_name
&& s.Server.Status.Name == status)
select new
{
ResourceGroupName = rg.Name,
ApplicationName = app.Name,
ServerName = srv.ServerName,
Alias = srv.Alias,
IPAddress = srv.IPAddress,
Type = rg.Type.Name,
Status = stat.Name
};
return query;
这是我在查询变量中得到的红线错误:
非常感谢您的帮助。 :)
谢谢,
雷
【问题讨论】:
-
EF 无法使用 include 部分加载关联属性,因此您需要使用
.Select()将其投影到视图模型(或匿名对象)中 -
@StephenMuecke,感谢您的回复。我已经用更多细节更新了我的问题。如果我删除所有
Includes,如何使用 lambda 语法选择语句?我可以用原生的sql查询来写,很简单,但是lambda让我很困惑。 -
保留包含(取决于是否启用延迟加载),然后使用
.Select(x => new MyModel(){ // set values here });其中MyModel是一个仅包含您想要包含在视图中的属性/集合的类.
标签: c# asp.net-mvc linq lambda