EF 4.1 - DBContext SqlQuery和Include [英] EF 4.1 - DBContext SqlQuery and Include

查看:585
本文介绍了EF 4.1 - DBContext SqlQuery和Include的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用DBContext SqlQuery执行原始sql,然后包含相关的entites。我尝试了以下但它没有加载相关实体:

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

任何帮助?

推荐答案

这是不可能的。 Include 仅适用于ESQL或linq-to-entities,因为必须在构建查询期间处理它以构造正确的SQL查询。您无法将SQL查询传递给此构造机制。此外,您的代码将导致执行SQL查询并尝试在结果枚举上调用 Include

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.

您可以也可以使用简单的linq查询来获得结果:

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;

这应该在SQL中产生内部联接,因此过滤器是非活动客户端。

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

这篇关于EF 4.1 - DBContext SqlQuery和Include的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆