Switches for LazyLoading with Repository pattern

天涯浪子 提交于 2019-12-08 04:50:33

问题


By default LazyLoading is disabled in my DbContext. I use repository pattern and in some case I need to get only simple object and in other I need to get object with values of navigations properties.

How can I implement something like switches for LazyLoading?
Any help will be appreciated

I have one solution that works but I'm not sure that it is correct: in interface of repository I added new property

    public interface IRepository<T> where T : BaseEntity
    {
        T GetById(object id);
        void Insert(T entity);
        .....
        bool LazyLoadingSwitches { set; }
    }

Then implemented it:

public bool LazyLoadingSwitches 
{
    set
    {
        this.context.Configuration.LazyLoadingEnabled = value;
    } 
}

and when I need to get model with related data then I use in controller:

repository.LazyLoadingSwitches = true;
name = order.Customer.FullName; 
repository.LazyLoadingSwitches = false;

Please suggest me what is the best solution for that?


回答1:


Just my two cents:

I think implementing a wrapper around the this.context.Configuration.LazyLoadingEnabled = value; call is OK. I would implement it as a method though, a write only property is quite odd.

In my coding I let the code that executes the query decide if it wants to use lazy loading or .Include statements. Most important is that the code that is going to consume the class that was returned finds all data in it that is needs.




回答2:


I think you can use include:

order.Include("Customer");
var name = order.Customer.FullName;

Sample with lambda expression:

order.Include(o => o.Customer);
var name = order.Customer.FullName;


来源:https://stackoverflow.com/questions/32771136/switches-for-lazyloading-with-repository-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!