我刚刚开始使用 .NET ORM,甚至还没有在 Entity Framework 和 NHibernate 之间做出决定。但在这两种情况下,我都遇到了一个问题,他们似乎希望我以各种看起来不自然的方式设计我的课程。这是有关该主题的几个问题之一。
示例类:
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;
}
}
在这种情况下,持久性逻辑有点复杂。我们希望保留私有initialAmount
和hasBeenDoubledYet
字段;重新实例化时,我们希望使用 调用构造函数,如果字段为 则initialAmount
调用。这显然是我必须编写一些代码的事情。Double()
hasBeenDoubledYet
true
另一方面,据我了解,典型的“ORM 友好”版本的代码可能最终看起来更像这样:
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 */ }
}
我在另一篇文章中谈到了我对默认构造函数和只读字段等的保留意见,但我想这个问题实际上是关于如何让 ORM 处理私有字段而不是私有属性——它可以在 EF 中完成吗?在 NHibernate 中?我们不能virtual
为代理目的标记字段……标记使用它们的方法virtual
就足够了吗?
这一切都让人觉得很老套:(。我希望这里的人能指出我错在哪里,无论是在我对他们能力的掌握中,还是在我对域建模和 ORM 角色的思考中。