Implementation of Entity Framework in Clean Architecture

Viewed 549

I am working on Clean Architecture and Entity Framework but confuse why we need to put Entity (database/ Table property Class) in Core project and DbSet--> DbContext in Infrastructure?? for me domain only concern with business entity which may not same as database entities/ Data Model and most important we are creating dependencies of data layer in Core and what happened when we table column change in database! is that means we change property in Core Project?

1 Answers

The reasoning behind this is that Entity Framework models in theory should be representative of your Business/Domain Model, and agnostic to your database storage strategy.

what happened when we table column change in database

Think of the Reason For Change behind most table column changes.

  • If you simply find that you have to rename that column to keep your database admins happy, you should be able to change the mapping (which resides in your Infrastructure project), and leave your Entity class intact.
  • If you're adding a new property, most likely that's because of a fundamental Domain Model change: you're adding some features that require that new property to be there on your Entity. This change will likely impact your core logic, your UI, and other parts of your code, so it makes sense for that change to start in the Core project and then require changes in the Infrastructure project to ensure that column is added to the database.

That said, in practice, there's a chance your Domain Model will end up reflecting your database storage strategy to some extent anyway. You'll invariably make design choices around how you store and retrieve data, which properties you'll expect to be populated, etc., based on the knowledge that you're working with an ORM like Entity Framework. If you decided to fundamentally change your data storage strategy (using a Document Store, e.g.) there's still a good chance your core logic would end up changing as a result. Nothing's perfect.

But if you adopt a mental model where your entities represent your Domain Model and the DbContext is merely an implementation detail related to how you store that model, you'll probably make it easier to do things like switching from a SQL Server instance to Azure SQL DB or some other compatible database provider, without having to shuffle core code around.

Related