简体   繁体   中英

How to retrieve different object types from IQueryable

I am using Entity Framework 5 code first. I have the following query that returns 2 different objects:

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 .

How do I retrieve the s and c objects from query because I need to work with them. 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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM