ORMs And Persistence Ignorance
Julie Lerman recently noted that Entity Framework can work with classes having private constructors and private property setters.
In the test published by Julie, you can see that Entity Framework (EF) is able to populate a property with private setters and invoke a private constructor without much difficulty. You can see how EF does this by referring the EntityProxyFactory and related classes, but in a gist, it’s a combination of reflection and IL Emits. NHibernate goes one step further and even supports accessing private fields (already being discussed for EF as well). However both currently require you to have a default constructor (even if it is non-public).
Architecturally, both Entity Framework and NHibernate support using patterns that help achieve persistence ignorance –
Entity framework has the DBSet and the DBContext respectively, whereas NHibernate has QueryOver api and the SessionContext. On the other hand, to support lazy loading, they also currently follow the virtual proxy pattern which goes against this principle (needs properties to be marked as virtual).
Persistence Ignorance is generally regarded as a good practice; business rules can be isolated from persistence logic, unlike, say when using Active Record pattern. This keeps the overall design simpler and more easily testable.
Tom Gilb & Kai Gilb Jan 26, 2015