问题描述
在EF 4中,是否可以通过在DbContext.Database.SqlQuery
或DbContext.Set<T>().SqlQuery
上编写sql来渴望加载导航属性?我似乎没有填充我的导航属性.
In EF 4, can I do eager loading of navigation properties by writing sql on DbContext.Database.SqlQuery
or DbContext.Set<T>().SqlQuery
? I don't seem to be getting my navigation properties populated.
修改
似乎我可以使用DbContext.Set().SqlQuery进行加载,而不能使用DbContext.Database.SqlQuery进行加载.知道为什么吗?
It seems I can do eagerloading with DbContext.Set().SqlQuery, just not DbContext.Database.SqlQuery. Any idea why?
推荐答案
DbSet.SqlQuery的工作原理不同于Database.SqlQuery. DbSet上的方法适用于给定的实体集.它必须返回给定类型的实体,默认情况下将跟踪返回的实体. Database.SqlQuery可以返回任何对象(可能不是实体),并且上下文永远不会跟踪返回的对象.您可能还想看看msdn来比较这两种方法:
DbSet.SqlQuery works differently than Database.SqlQuery. The method on DbSet applies to the given entity set. It has to return entities of the given type and by default the returned entities will be tracked. Database.SqlQuery can return any object (possibly not an entity) and the returned objects are never tracked by the context. You may also want to take a look at msdn to compare both methods:
Database.SqlQuery- http://msdn .microsoft.com/en-us/library/gg679117(v = vs.103).aspx
Database.SqlQuery - http://msdn.microsoft.com/en-us/library/gg679117(v=vs.103).aspx
DbSet.SqlQuery- http://msdn.microsoft.com/zh-cn/library/system.data.entity.dbset.sqlquery(v = VS.103).aspx
DbSet.SqlQuery - http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=VS.103).aspx
这篇关于使用DbContext.Database.SqlQuery在EntityFramework中快速加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!