2

I'm building REST APIs with ASP.NET Core and Entity Framework Core with a database-first approach with clean architecture.

My database is already created and maintained by a DBA team - that's why I need to use Entity Framework Core with a database-first approach, and we need to do reverse engineering using the Scaffold-DbContext command in the infrastructure layer.

With clean architecture, entities should be placed in Core layer separate from the infrastructure layer so how we will do that and how to resolve your DbContext as an interface.

1
  • I'm not sure I understand your question, but if you ask how to abstract DbContext, repository pattern probably will help. Feb 21, 2020 at 10:01

1 Answer 1

2

I see two options:

  1. You accept the dependency to the EF, put the generated entities into your core project and so accept the violation to clean architecture.

  2. You create your own entities in Core project without dependencies to EF and use repository pattern to "map" between your entities and those from EF.

Alternative 1 is simple and cheap. Alternative 2 gives you independence from EF and some abstraction to your dba team. Choose based on what is more important for your project.

4
  • I would select 1 option. Is it best practice to move auto generated db entities from Persistence Layer to Domain Layer (generated by Scaffold-DbContext command)? is there any command to generate db entities in separate layer and db context in separate layer? Mar 2, 2020 at 13:05
  • It all depends on what you want to optimize for: do you need rapid prototyping and is your code base small? Option 1 might be best. Do you need independence from other teams, specific frameworks and technologies and your code base is big and needs to be maintained for years: go for option 2. (I am not aware of such command) Mar 2, 2020 at 21:13
  • @plainionist how would you do option 2? With a generic base repository? Jan 21 at 21:20
  • you not necessarily need a "base repository" - just have your domain entities separate and then create a set of DTOs optimized for persistency and EF. Then create a "repository" class which does the EF operations based on EF DTOs and then "manually" map those DTOs to your domain entities (copy values from one type to the other) Check out this video for more: youtu.be/pfhDO_hZixw Jan 22 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.