How to map Entity Framework model classes with Business Layer class in n-tier architecture - ASP.NET-MVC

后端 未结 3 1442
我在风中等你
我在风中等你 2021-02-10 03:13

I am working on e-tier architecture within MVC framework (ASP.NET MVC5, Entity Framework 6). My application is divided into three sub-projects which are Business-Layer, Data-Acc

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 03:40

    Firs of all there is no need for both Repository Layer and Data Access Layer. Those 2 layers have the same purpose - to add a layer of abstraction for working with your persistent storage. Although they have different concepts

    1. Repository pattern basically provides you with a way to work with your db as if it was an in memory collection. Most of the time it exposes basic CRUD (create read update and delete) methods with some other extensions such as GetAll method and etc. This is a very simplified description but there are enough resources about this pattern for example.
    2. Data Access Layer also adds an abstraction but in much more subjective way. Basically it Contains all the API for accessing you DB. For example for your User class it could have methods such as GetUserByName, GetUserById, RemoveUser, GetAllActiveUsers and etc.

    Also Unit of Work doesn't have to be implemented in Repository/DAL. Since a single unit of work can contain modification of multiple entities or requests to external services. In my opinion BLL would be a more suitable place for UoW since in most of the cases you can look at a single business action (a method in BL) as a UoW

    Now when this is a little clearer (hopefully). Your Repository/DAL should return only Business entities and not a data base generated classes (in case that they are different) and all the mapping logic should be encapsulated inside the Repository/DAL Layers. For example GetUserById method should return a BLL - User Class and not a User Class generated by EF in this case which can be internal class to the Repository/DAL layer.

    For handling mappings between those classes you can use different libraries such as ValueInjecter or AutoMapper which are really great and can make your development much easier.

提交回复
热议问题