2011-03-15 46 views
1

虛擬呼叫我有一個實體宣稱與此類似:流利NHibrnate - 在構造 - 最佳實踐

public class Comment 
{ 
    public Comment(string text, DateTime creationDate, string authorEmail) 
    { 
    Text = text; 
    CreationDate = creationDate; 
    AuthorEmail = authorEmail; 
    } 

    public virtual string Text { get; private set; } 
    public virtual DateTime CreationDate { get; set; } 
    public virtual string AuthorEmail { get; private set; } 
} 

我從Is it OK to call virtual properties from the constructor of a NHibernate entity?

採取它我得到警告爲「在構造虛擬呼叫」。

雖然它不會造成任何實際問題,因爲虛擬成員只是爲NH代理而聲明的。但是,如果我應該移動的構造方法到一個新的工廠用新的方法,我在想,被宣佈爲

CreateComment(string text, DateTime creationDate, string authorEmail) 

什麼會在這種情況下,最好的做法是什麼?

請注意,目前我的域實體中有4-5個重載構造函數。以上只是一個例子。
謝謝!

回答

0

我喜歡有一個參數(缺省)構造和建造像這樣:

var comment = new Comment { 
        Text = "Something offensive and political.", 
        CreationDate = DateTime.Now, 
        AuthorEmail = "[email protected]" 
       }; 

現在的問題並不重要。

+0

怎麼樣,我需要從外面傳值的方法:(字符串文本,日期creationDate,串AUTHOREMAIL) – iniki 2011-03-15 16:05:48

+0

@iniki:Huh?I不明白你的意思,因爲你可以簡單地說'var comment = new Comment {Text = GetText(),CreationDate = GetCreationDate(),AuthorEmail = GetAuthorEmail()};' – jason 2011-03-15 16:32:02

+0

Jason對不起,但我想我是在這裏忽略了你的觀點:-(實際上,我現在所需的重載構造函數需要將對象成員設置爲從客戶端應用程序接收的值。不知道我怎麼能在無參數的構造函數中做到這一點。你能否詳細說明你的答案? – iniki 2011-03-16 12:20:40

0

如果你的屬性僅是虛擬的,以適應NHibernate的,你可以讓他們封裝具體領域(NHibernate的知道如何應對是:看here(默認訪問)和here(訪問)
它用流利的支持。NH以及

1

我與FluentNHibernate測試,你可以做這樣的:

public class Comment 
{ 
    private string _text; 
    private DateTime _creationDate; 
    private string _authorEmail; 

    public Comment(string text, DateTime creationDate, string authorEmail) 
    { 
     _text = text; 
     _creationDate = creationDate; 
     _authorEmail = authorEmail; 
    } 

    public virtual string Text 
    { 
     get { return _text; } 
     private set { _text = value; } 
    } 

    public virtual DateTime CreationDate 
    { 
     get { return _creationDate; } 
     set { _creationDate = value; } 
    } 

    public virtual string AuthorEmail 
    { 
     get { return _authorEmail; } 
     private set { _authorEmail = value; } 
    } 
}