Entity Framework – Avoiding the Anemic Domain Model

business-logiccdomain-modelentity-framework

In our business logic we occasionally have methods defined something like this:

User.ResetCourse(Course courseToReset)

The problem is that both User and Course are Entity Framework proxy objects. This means that when we hit navigation properties on either User or Course it can cause a huge hit to the database because those objects are not IQueryable so it iterates through them normally.

To solve this we changed the signature to:

User.ResetCourse(MyDBContext db, Course courseToReset)

This means we can directly query the database to make the changes we need in an efficient manner but passing the Database context to a business object just seems so wrong.

We later migrated to user a service layer which means we have something like:

CourseService.ResetForUser(Course courseToReset, User forUser)

This service has a reference to the DBContext injected in on creation but now our business objects are just data bags with no behaviour (i.e an Anemic Domain Model).

How can we avoid this?

Best Answer

The issue is, you are using EF objects as domain objects in the first place. EF objects are data models NOT business models.

You need to declare business objects which give you the freedom to do as you need, and then retrieve and store them with a repository. Your repository will map the EF entities to your business entities. EF objects should never be used outside of your repositories.