[英]How to retrieve different object types from IQueryable
I am using Entity Framework 5 code first. 我首先使用Entity Framework 5代码。 I have the following query that returns 2 different objects:
我有以下查询返回2个不同的对象:
var query = (from s in DatabaseContext.Servers
join c in DatabaseContext.CommandExecutionServers on s.Domain equals c.Domain
where s.Id == serverId && c.Active == active
select new { s, c });
s is a Server class
and c is a CEServer class
. s是
Server class
而c是CEServer class
。
How do I retrieve the s and c objects from query because I need to work with them. 如何从查询中检索s和c对象,因为我需要使用它们。 I need something like:
我需要类似的东西:
Server server = s; // first check for nulls and
server.CEServer = c; // check for nulls as well
Since your query returns a sequence of objects of anonymous class, you can enumerate your query, and access s
and c
from each returned row, like this: 由于查询返回了一系列匿名类的对象,因此您可以枚举查询,并从返回的每一行访问
s
和c
,如下所示:
foreach (var row in query) {
Server s = row.s;
// Check the server...
CEServer c = row.c;
// Use CEServer...
}
If you sure that you will get only and exact one pair, you can use this: 如果您确定只得到一对,那么可以使用以下方法:
Server server = query.Single().s; // first check for nulls and
server.CEServer = query.Single().c;
if no, you will get exception . 如果没有,您将获得exception 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.