从数据库加载没有代理类?
在entity framework4中是否可以选择在没有使用代理类的情况下将某些查询加载到POCO中? (出于缓存该对象的目的,以备将来只读使用)。 我正在使用存储库 – 服务模式。
我的意思是:
var order = _orderService.GetById(1); // after order is loaded then we can see in the debugger that: // order.Customer is of type System.Data.Entity.DynamicProxy.Customer_17631AJG_etc
我想要的是order.Customer
实际使用POCO类型MyApp.Models.Entities.Customer
而不是该类型的代理。
编辑:根据Ladislav建议在存储库中添加“GetUnproxied”方法,我做了这个改动:
// this is the current method that must return a DynamicProxy public IQueryable GetQuery() { return ObjectSet.AsQueryable(); } // this is the new additional method that must return the plain POCO public IQueryable GetReadOnly() { ObjectContext.ContextOptions.ProxyCreationEnabled = false; var readOnly = ObjectSet.AsQueryable(); ObjectContext.ContextOptions.ProxyCreationEnabled = true; return readOnly; }
它是否正确?
它对我来说看起来不安全。 两种方法都使用相同的ObjectContext实例,因此可能在一个线程上发生ProxyCreationEnabled == false
,然后在另一个线程上调用public IQueryable GetQuery()
– 这会突然意味着代理方法可能返回非代理对象。
在查询数据以关闭代理创建之前使用此选项
context.ContextOptions.ProxyCreationEnabled = false;
我认为它也可以在EDMX设计师的全球范围内关闭。
更新:
这适用于ObjectContext
。 使用DbContext
代码是:
context.Configuration.ProxyCreationEnabled = false;
另外,我在edmx设计器中看不到任何选项
上述就是C#学习教程:从数据库加载没有代理类?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/999717.html