문제

I would like to have one dbcontext with lazy-loading enabled for writes, and another dbcontext with lazy-loading disabled for reads. Both should work on the same model. I would like to inject the 2 dbcontexts after constructing them with lazy loading settings into the service class and use each of them where appropriate.

Is this even possible?

I guess I am trying to avoid having to set lazyloading to false inside the service methods.

도움이 되었습니까?

해결책

You can, but it's probably a bad idea. You won't be able to use an entity retrieved from one context with the other (not directly anyway). To write to an entity retrieved using the "read" context you'll have to read it again using the "write" context in order to modify it.

Instead, you can simply enable or disable lazy loading as needed before you make use of your context.

DbContext.Configuration.LazyLoadingEnabled = false; //or true

You could make it easier by simply defining a custom constructor for setting the LazyLoading attribute.

public MyDbContext(bool LazyLoad)
        : base(nameOrConnectionString: "MyDbContext") {
            this.Configuration.LazyLoadingEnabled = LazyLoad;
}

If you really really need to, you could subclass your DbContext and set LazyLoading in the constructor, but it just seems like a bad idea.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top