EF 4.1 - DBContext SqlQuery and Include
Asked Answered
M

2

7

I want to execute a raw sql using DBContext SqlQuery and then include related entites. I've tried the following but it doesn't load the related entities:

string sql = "Select * from client where id in (select id from activeclient)";
var list = DbContext.Database.SqlQuery<Client>(sql).AsQueryable().Include(c => c.Address).Include(c => c.Contactinfo).ToList();

Any help?

Michael answered 28/9, 2011 at 9:52 Comment(0)
M
6

It is not possible. Include works only with ESQL or linq-to-entities because it must be processed during query building to construct correct SQL query. You cannot pass SQL query to this construction mechanism. Moreover your code will result in executing SQL query as is and trying to call Include on resulted enumeration.

You can also use simple linq query to get your result:

var query = from c in context.Clients.Include(c => c.Address).Include(c => c.Contactinfo)
            join ac in context.ActiveClients on c.Id equals ac.Id
            select c;

This should produce inner join in SQL and thus filter are non-active clients.

Maurilla answered 28/9, 2011 at 11:34 Comment(0)
D
1

Not direct answer, but instead of writing raw sql query you could use something like this

_conext.Clients.Where(c => _conext.ActiveClients.Any(a => a.ClientId == c.Id));
Donovan answered 28/9, 2011 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.