EF 4.1 - DBContext SqlQuery and Include

时间秒杀一切 提交于 2019-12-04 03:20:00

问题


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?


回答1:


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.




回答2:


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));


来源:https://stackoverflow.com/questions/7581352/ef-4-1-dbcontext-sqlquery-and-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!