SOf*_*tic 7 c# entity-framework-6
我有这个SQL查询:
SELECT
t.ServerId, t.Id, s.Name
FROM
MyTable as t
JOIN
Server s ON t.ServerId = S.Id
Run Code Online (Sandbox Code Playgroud)
我正在运行它:
context.Database.SqlQuery<entity>("query_goes_here");
Run Code Online (Sandbox Code Playgroud)
如何配置EF以便它Server使用查询的返回数据加载我的实体的属性?
基于@octavioccl的答案,我最终做到了这一点:
foreach(var result in results)
{
context.Attach(result);
context.Entry(result).Reference(p => p.Server).Load();
}
Run Code Online (Sandbox Code Playgroud)
但是我担心这会造成很多数据库的旅行?
将该DbSet.SqlQuery方法用于返回实体类型的查询.返回的对象必须是对象所期望的类型DbSet,并且除非您关闭跟踪,否则它们将由数据库上下文自动跟踪.
var enties= _context.Entities.SqlQuery("query_goes_here");
Run Code Online (Sandbox Code Playgroud)
执行查询后,你应该能够获取Server通过您entity通过延迟加载实例:
var server=entity.Server;
Run Code Online (Sandbox Code Playgroud)
另一方面,Database.SqlQuery即使您使用此方法检索实体类型,数据库上下文也不会跟踪返回的数据.如果要跟踪使用此方法执行查询后获得的实体,可以尝试以下操作:
//Attach the entity to the DbContext
_context.Entities.Attach(entity);
//The Server navigation property will be lazy loaded
var server=entity.Server;
Run Code Online (Sandbox Code Playgroud)
如果您已禁用延迟加载,则可以使用以下DbEntityEntry.Reference()方法显式加载导航属性:
//Load the Server navigation property explicitly
_context.Entry(entity).Reference(c => c.Server).Load();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3508 次 |
| 最近记录: |