我剛剛開始使用.NET ORM,甚至沒有在實體框架和NHibernate之間做出決定。但在這兩種情況下,我遇到了一個問題,他們似乎希望我以各種不自然的方式設計我的課程。這是關於這個問題的幾個問題之一。.NET ORMs和持久非屬性狀態
實施例類:
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
字段;當重新實例化時,如果hasBeenDoubledYet
字段爲true
,我們想調用構造函數initialAmount
,並調用Double()
。這顯然是我必須寫一些代碼的東西。
在另一方面,典型的「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 */ }
}
我介紹了有關默認構造函數和只讀我的預訂字段等在another post,但我想這個問題是關於如何讓ORMs處理私人領域,而不是私人屬性 - 可以在EF中完成嗎?在NHibernate中?我們不能標記字段virtual
代理的目的......會標記使用它們的方法virtual
就足夠了嗎?
這一切都感覺那麼哈克:(。我希望這裏有人能指出我的錯了,無論是在我自己的能力把握或在我的有關域建模和奧姆斯的角色思考。
因爲你是濫用ORM什麼是設計感覺「哈克」 for;你正試圖在實體對象內部做業務邏輯;一些參考http://en.wikipedia.org/wiki/O-RM,如果你做簡單的搜索,我相信還有更多 – 2011-03-19 20:46:03
@K Ivanov:我承認我在這方面是一個新手,但這意味着它是一個領域驅動設計意義上的實體,所以業務邏輯確實在那裏。我認爲ORM的工作是在數據庫和域對象之間進行翻譯。你是說在數據庫和我的領域層之間應該有一個「實體對象」的中間層? – Domenic 2011-03-19 20:58:21