I am just getting started with .NET ORMs, to the point where I haven't even decided between Entity Framework and NHibernate. But in both cases, I'm running into a problem in that they seem to want me to design my classes in various ways that seem unnatural. This is one of several questio开发者_如何学JAVAns on the subject.
Example class:
public class Pledge // this is an entity BTW, not a value object
{
private readonly int initialAmount;
private bool hasBeenDoubledYet;
public Pledge(int initialAmount)
{
this.initialAmount = initialAmount;
}
public int GetCurrentAmount()
{
return this.hasBeenDoubledYet ? this.initialAmount * 2 : this.initialAmount;
}
public void Double()
{
this.hasBeenDoubledYet = true;
}
}
In this case the persistence logic is a bit complicated. We would want to persist the private initialAmount
and hasBeenDoubledYet
fields; when re-instantiating, we would want to call the constructor with initialAmount
, and call Double()
if the hasBeenDoubledYet
field is true
. This is obviously something I'd have to write some code for.
On the other hand, the typical "ORM friendly" version of the code would probably end up looking more like this, as far as I understand:
public class Pledge
{
// These are properties for persistence reasons
private int InitialAmount { get; set; } // only set in the constructor or if you are an ORM
private bool HasBeenDoubledYet { get; set; }
private Pledge() { } // for persistence
public Pledge(int initialAmount) { /* as before but with properties */ }
public int GetCurrentAmount() { /* as before but with properties */ }
public int Double() { /* as before but with properties */ }
}
I covered my reservations about default constructors and readonly fields etc. in another post, but I guess this question is really about how I could get ORMs to handle private fields instead of private properties---can it be done in EF? In NHibernate? We can't mark fields virtual
for proxying purposes... would marking the methods that use them virtual
suffice?
It all feels so hacky :(. I am hoping that someone here can point out where I am wrong, either in my grasp of their capabilities or in my thinking about domain modeling and the role of ORMs.
I don't know about EF, but NHibernate needs the properties you want to persist to be virtual and public (as you said for proxying reasons).
精彩评论