Brendan Vogt
Brendan Vogt

Reputation: 26048

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

Upvotes: 1

Views: 122

Answers (2)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

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...
}

Upvotes: 1

Related Questions