简体   繁体   中英

Access the Entity Framework model classes in API controller

Project Architecture is like this:

  • MyProject.DataAccessLayer : will communicate with database using Entity Framework

  • MyProject.BusinessLayer : application business logic will be here

  • MyProject.API : WebAPI ApiControllers will return the data from business layer methods

My question is that, if I have created an Entity Framework as separate project in the DataAccessLayer , how can I use the model classes from the DataAccessLayer ?

Should I add a reference to MyProject.API to access the model classes? If this is the case, why would I need the MyProject.BusinessLayer ?

Edited

Sample code for business layer:

  public async Task<List<TigerNest.Dao.Area>> GetArea()
          => await yatraDao.GetArea();

ApiController :

YatraManager manager = new YatraManager();
var result = await manager.GetArea();
return Ok(result);

In the ApiController , the BusinessLayer returns a collection of areas. It forces me to add reference to the Dao project.

If I have created Entity Framework as separate project in DataAccessLayer , how can I use the model classes from DataAccessLayer ?

You can put the model classes into an independent project infrastructure

Should I add a reference to MyProject.API to access the model classes?

Yes, because you need to return data from API

If this is the case why do I need MyProject.BusinessLayer ?

I suggest you might create a Myproject.BusinessLayer , because the business layer can place repetitive logic for later reuse.

We separate UI , BusinessLayer , DataAccessLayer those can reference with infrastructure project, infrastructure will use the model, container ..

在此处输入图片说明


Edit

In brief, the UI layer is referenced to the BLL and the BLL is referenced to the DAO,and they all refer to the Infrastrure (DTO, ViewModel) common layer

In your question you might mapping EF model be DTO model on BusinessLayer , ApiController can use the DTO model .

So ApiController and BusinessLayer refer a new project Infrastrure ,that put DTO or ViewModel ,This way you can isolate the EF Model.

DTO (data transfer object) is like ViewModel but he exists in data conversion. EF Model corresponds to DB schema, DTO corresponds to EF Model.

DTO model should contain only data and not business logic.

I recommend a third party kit AutoMapper ,that helps us to map objects more easily.


There are some article talk about AutoMapper and 3-Tier-Architecture

Easily Generate Data Transfer Objects from ADO.NET Entity Framework or LINQ to SQL Data Classes

Mapping Entity Framework Entities to DTOs with AutoMapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM