使用存储库模式切换LazyLoading
默认情况下,在我的DbContext中禁用了LazyLoading。 我使用存储库模式,在某些情况下,我只需要获取简单的对象,而在其他情况下,我需要获取具有导航属性值的对象。
如何为LazyLoading实现类似开关的东西?
任何帮助将不胜感激
我有一个有效的解决方案,但我不确定它是否正确:在存储库的界面中我添加了新属性
public interface IRepository where T : BaseEntity { T GetById(object id); void Insert(T entity); ..... bool LazyLoadingSwitches { set; } }
然后实现它:
public bool LazyLoadingSwitches { set { this.context.Configuration.LazyLoadingEnabled = value; } }
当我需要获取相关数据的模型时,我在控制器中使用:
repository.LazyLoadingSwitches = true; name = order.Customer.FullName; repository.LazyLoadingSwitches = false;
请建议我最好的解决方案是什么?
只是我的两分钱:
我想在this.context.Configuration.LazyLoadingEnabled = value;
周围实现一个包装器this.context.Configuration.LazyLoadingEnabled = value;
打电话没问题。 我会把它作为一种方法实现,但是只写属性很奇怪。
在我的编码中,我让执行查询的代码决定是否要使用延迟加载或.Include
语句。 最重要的是,将使用返回的类的代码会查找所需的所有数据。
我想你可以使用include:
order.Include("Customer"); var name = order.Customer.FullName;
lambda表达式的示例:
order.Include(o => o.Customer); var name = order.Customer.FullName;