I am using Entity Framework Model-First with Repository
and Unit of Work
patterns, the repositories return EF POCOs.
I assumed that I couldn’t add behaviour to my POCOs that are generated by Entity Framework, so my code is now full of things like XyzService
which is a separate class implementing the business logic for the Entity Framework generated Xyz POCO
.
I have the following questions:
This has a bad code smell as not only do I have the EF POCOs, I have a service for each POCO. In addition to lots of classes, business logic is split outside of the business entity. Is this an example of the anaemic anti-pattern?
If I stick with EF, is there any way I can add behaviour (i.e. through partial classes) or other means?
Seeing the persistent ignorant patterns which use return business entities from data layer (in our case a repository), if I wanted to go from EF-MODEL -> REPOSITORY-DAL -> BIZ-ENTITY
I see there would be a lot of two way mapping between the business entity and the EF model POCO. Can utilities such as Automapper gracefully handle complex relationships of nested objects that I am likely to face?
To reduce duplicated business entities with their counterpart EF model entities, would I not be better of removing EF and just writing my own repository implementations using LINQ to SQL for each repository?
Any recommended way that allows me to concentrate on the code (rather than target fixating on the EF model first as I have been), then still use Entity Framework at the end when I am ready to write the persistence layer, but avoiding a lot of extra work and mapping in doing so? Would EF Code-First be better in this regard?
If I have missed anything else of other technologies that can aid development (NHibernate for example) then please feel free to mention.
Keep in mind that partial classes cannot span multiple assemblies (from MSDN):
All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
This restriction could be undesirable, though you could instead use extension methods to implement the required behaviour.
I've not used Automapper, so Ryan's advice would apply here.
In terms of repositories, my preference is for the repository to be completely generic in terms of both the POCO types we are dealing with, and the operations available. For example, with LINQ a repository could have a Get
method that retrieves items (say, as an IEnumerable<T>
) based upon a given Expression<Func<T, bool>>
.
I like this approach because it allows the repository to be dependency injected, cleanly separates standard CRUD operations from more domain-specific ones, yet offers great opportunities for code reuse from consumers/derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With