[英]how to compose view models and minimize database interaction at the same time
In Asp.Net MVC with Entity Framework, I totally agree that repositories in the DAL (Data Access Layer), which is located in a separate assembly, must not deal with view models. 在带有Entity Framework的Asp.Net MVC中,我完全同意DAL(数据访问层)中的存储库(位于单独的程序集中)不得处理视图模型。
From the DAL I get entities, mostly IQueryAbles. 从DAL中,我得到实体,主要是IQueryAbles。 From those I compose quite complex view models.
从这些我组成了相当复杂的视图模型。 The challenge is that I want to minimize the number of sql selects generated in order to compose a view model.
挑战在于,我想最大程度地减少为了组成视图模型而生成的sql选择的数量。 In some cases, I need to query the db 10-20 times.
在某些情况下,我需要查询数据库10-20次。
for example, this is my view model 例如,这是我的视图模型
class ViewModel{
//.. public properties mapped from entities 1 sql select
public int CountOfSomething {get; set;} 1 sql select
public int CountOfSomethingElse {get;set;} 1 sql select
//..and so on
}
So this is not optimal, from a performance perspective. 因此,从性能角度来看,这不是最佳选择。 I could modify the repositories to return much more complex results, but then they would not return entities, but something else.
我可以修改存储库以返回更复杂的结果,但随后它们将不返回实体,而是返回其他东西。
In that case: DAL composes and returns an intermediate model (entity(s) plus additional data) which is defined in the DAL assembly, and THAT intermediate model, and not an entity, is then translated into a view model. 在这种情况下:DAL组成并返回在DAL程序集中定义的中间模型(实体和其他数据),然后将该中间模型(而不是实体)转换为视图模型。
DB -> Entity -> Intermediate model -> ViewModel DB->实体-> 中间模型 -> ViewModel
This additional "mapping" requires more code == more complexity. 这种额外的“映射”需要更多的代码==更高的复杂性。 I am not sure how to tackle this problem now.
我不确定现在如何解决这个问题。
Until now I have solved some cases with creating additional "helper" repository methods, but I realize it very rapidly becomes a bit of a mess. 到目前为止,我已经通过创建其他“帮助程序”存储库方法解决了一些情况,但我意识到它很快变得一团糟。
Any ideas? 有任何想法吗?
Make some classes which job is only to map from the entity/intermediate model to the viewmodel. 制作一些类,仅将其从实体/中间模型映射到视图模型即可。
There are some libraries out there for that purpose, I recommend you automapper , it even has some testing functionalities so you can do your mappings properly. 为此,有一些库,我建议您使用automapper ,它甚至还具有一些测试功能,因此您可以正确地进行映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.