Search code examples
entity-frameworkasp.net-web-apiweb-applicationsdata-access-layern-tier-architecture

Entity Framework layer with crud methods called in webapi need reference to entities in data layer


My web application in ASP.NET uses Angular as its frontend. For database and API, I made 3 projects in the solution. API, BOL and Entity Framework.

  • BOL has all the POCO classes.
  • Entity Framework has the DbContext class and the connection string to the SQL Server database. It also has the reference to BOL. All the repositories with insert, update, delete and get methods for every entity are there too.
  • API has the API controllers with crud functionality which call the methods from the Entity Framework project. It has a reference to Entity Framework project.

But when I try to call a method from Entity Framework on the instance of the respective repository, it asks to add reference to BOL. But it should not use BOL as that ruins the purpose of the Entity Framework project


Solution

  • it depends how you are using the POCO classes.

    if the EF project uses POCO classes to return results and your API calls methods inside the EF project then you will need a reference to BOL because otherwise the API project doesn't know how to deal with the results.

    The fact that both the EF and the API project have references to BOL is not an issue, it's exactly as it should be, since both use these models and that's why you separated the models in the first place. You want them to be shared.

    So bottom line, if the EF projects takes input or returns data using the BOL classes then you need to add a reference to that project in your API project.

    Now, for the second issue with the connection string having to be in the API project, that will have to stay that way. The reason is because of how the framework works.

    You have a main project and you reference a class library. When you compile the solution, the EF dll get built and copied over to the API project. At that point it will use the settings of the API project, not its own. This is why connection string needs to be in the API project as well. Looks inside the APIs bin folder and you'll see what I mean.