Question

I'm not sure I can even articulate this properly but...

I'm starting to architect a solution using code-first Entity Framework and am beginning to get the feeling I'm polluting my domain classes (the classes EF will use to generate the DB) with too much DB-specific information: I have to make certain methods virtual in order that lazy loading can occur, I'm adding attributes clearly aimed at DB configuration to my properties, and so on. I'm also concerned about how pervasive these classes are going to be throughout the project.

Firstly, am I making sense and/or am I fundamentally misunderstanding how EF should be used?

Secondly, if I'm understanding this right, my question is: does anyone else make a distinction between their code-first classes used to generate their DB and their domain classes (perhaps using an auto-mapper to populate one from the other)?

Was it helpful?

Solution

I've spent a long time trying out different approaches to this problem. In its simplicity it's possible and very easy with Entity Framework to use the data classes as domain classes as well.

My experience is that in small projects you can get away with using your EF classes as your domain classes. This is fast and simple, however as the projects grow larger this start to become and issue since you can't control the access in any way.

The most common scenario is when exposing navigation properties on EF classes. Your whole application will now be able to navigate your entire data set. So with this model you give up all control over your data and domain objects.

There are several advantages to having your domain classes separately from EF. First of all you will not be as heavily tied to EF or code-first. With a level of separation/indirection you will be able to swap out your data framework should you desire so. Secondly you are able to control your data much more effectively.

Personally I've reached a pragmatic point where I take this decision at the start of every project. If the project is small and contained then I might avoid this extra abstraction in favor of simplicity. In almost ever medium-large and/or large project I've the separation.

OTHER TIPS

If you are going to use SOLID principles in your coding, you really should separate your data implementation (in your case EF code first) from your domain/business logic. Mapping them is a bit of an overhead, but consider what happens when you need to access some data from web services?

In addition, your domain classes will often contain calculated or derived values (eg Full Name, Address) that will not be present in your database classes and potentially vice versa (eg database logging info)

I'd do a search for the repository pattern in the first instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top