MavisBeacon MavisBeacon - 3 months ago 30
C# Question

Duplicating POCO code in different layers with code-first migrations

I'm interested in using entity framework - code first migrations with a new database, and I have some questions/concerns about duplicating POCO code in the data and business layers.

The idea is to have a data access layer containing my POCO entities all decorated with database schema type items like string lengths, foreign key related things that don't work out of the box, and whatever else. This layer will also act as a repository that will return scalar values, entities, aggregates, and IEnumerables.

Above that will be the business layer, which will handle talking to the repository, and a bunch of business logic.

At the top is the presentation layer. This layer talks to the business layer, and has no idea about the data layer – all it understands is view models. I would implement the MVC pattern at this layer, using only view models.

The issue I am running into is related to where I should do the mapping between my view models and my data models. If I define the view models in my presentation layer, the business layer will not know they exist.

  • Am I better off defining the view models in the business layer, or do I need a set of domain models in the business layer that the presentation layer would be aware of and be able to perform mapping against?

    • Would an additional set of domain models just be an egregious duplication of the models defined in the data layer?


Depending on the scope of the project, I usually use one of the two methods below:

1) have a set of domain models separately from all layers, and then have all layers reference them. Pros: layers are still independent, no model duplication, no need to map layer models. Cons: change in domain model would affect all layers, e.g. DB change may break display

2) have models in each layer. Business layer would map its own models to those of data layer, presentation layer would map its models to those of business layer Pros: every layer does one thing, changes in underlying models to not propagate through layer Cons: duplication of the models is likely and mapping needs to be maintained

First approach works best for smaller apps and "direct updates" scenarios, second works better in large projects with multiple moving components.

P.S. "defining the view models in the business layer" is a definite no-no.