使用CTP4过滤DBContext [英] Filtering on DBContext using CTP4

查看:73
本文介绍了使用CTP4过滤DBContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CTP4我有一个DbContext来模拟我的数据库,但是数据库表都有软删除字段。


当我通过存储库查询它时这很好用


 


 Context.Where(x = > x.IsDeleted ==  false  
);

解决方案

wduffy,


 


现在没有一种简单的方法可以做到这一点。 
我唯一能想到的就是你可以关掉延迟加载,然后自己明确处理集合的加载。 
您必须下拉到ObjectContext才能在CTP4中执行此操作。 
要关闭延迟加载,请从DbContext上的protected属性获取ObjectContext,然后使用ObjectContext.ContextOptions.LazyLoadingEnabled = false。 
或者,不要将您的任何导航属性设置为虚拟,以便EF不会为您的实体创建代理
  和赢得了延迟加载。


 


一旦延迟加载被禁用,您将必须管理创建将集合的实体加载到上下文中的查询。 
不幸的是,这意味着在实体中有一个上下文(这是代理所做的,但它会破坏POCO类的持久性无知)或者使用一些服务来加载每个集合。 
(如果您知道在返回实体时需要填充哪些集合(急切加载),那么您可以在存储库中完成所有这些。)


 


一旦有了上下文,就可以编写一个普通的查询来实现实体上下文使用来自委托人的PK来决定要加载哪些实体。 
您还可以在IRelatedEnd上查看CreateSourceQuery,但是为POCO实体获取相关的结束并不是一件容易的事情,所以如果你能用正常的查询来做,那么我希望它会更干净。 
这里的关键是,当实体被物化到上下文中时,它们将自动添加到集合导航属性中。


 


对不起,这并不容易;希望这有点帮助。


 


谢谢,


亚瑟


Using CTP4 I have a DbContext which models my database however the database tables all have soft delete fields.

This works fine when I query them via a repository

 

Context.Where(x => x.IsDeleted == false
);

解决方案

wduffy,

 

There is not an easy way to do this right now.  The only thing I can think of is that you could switch off lazy loading and then handle the loading of collections explicitly yourself.  You have to drop down to the ObjectContext to do this in CTP4.  To switch off lazy loading, get the ObjectContext from the protected property on DbContext, then use ObjectContext.ContextOptions.LazyLoadingEnabled = false.  Alternatively, don’t make any of your navigation properties virtual such that the EF doesn’t create proxies for your entities  and won’t do lazy loading.

 

Once lazy loading is disabled you will have to manage creating the queries that will load the entities for the collection into the context.  Unfortunately this means having a context available in the entity (which is what the proxies do, but which will break persistence ignorance for your POCO classes) or use some service to load each collection.  (If you know which collections you will need populated when you return the entity (eager loading) then you could do it all in the repository.)

 

Once you have a context you can write a normal query to materialize the entities into the context using the PK from the principal to decide which entities to load.  You could also look at CreateSourceQuery on IRelatedEnd, but it’s not trivial to get the related end back for a POCO entity so if you can do it with normal queries, then I expect that will be cleaner.  The key here is that as the entities are materialized into the context they will automatically be added to the collection navigation property.

 

Sorry this isn’t easier; hope this helps a bit.

 

Thanks,

Arthur


这篇关于使用CTP4过滤DBContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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