EF 4.1 - DBContext SqlQuery and Include

2019-02-21 20:13发布

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?

2条回答
叛逆
2楼-- · 2019-02-21 20:50

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.

查看更多
我命由我不由天
3楼-- · 2019-02-21 20:51

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));
查看更多
登录 后发表回答