2017-10-16 289 views
0
自定義對象

請參閱下面的域對象:我如何使用與NHibernate

public Class Person 
{ 
    public virtual Guid Id { get; protected set; } 
    public virtual string FirstName { get; protected set; } 
    public virtual string Surname { get; protected set; } 
    public virtual System.DateTime DateOfBirth { get; protected set; } 

     //Domain methods are here. 

} 

及以下NHibernate的映射:

public class PersonMap : ClassMapping<Person> 
{ 
    public PersonMap() 
    { 
     Id<Guid>(x => x.Id); 
     Property<string>(x => x.FirstName); 
     Property<string>(x => x.Surname); 
     Property<DateTime>(x => x.DateOfBirth); 
    } 

}

可正常工作。假設我想將領域模型更改爲:

public Class Person 
{ 
    public virtual Guid Id { get; protected set; } 
    public virtual FirstName FirstName { get; protected set; } 
    public virtual Surname Surname { get; protected set; } 
    public virtual DateOfBirth DateOfBirth { get; protected set; } 
} 

注意原始類型被替換爲對象。我這樣做的原因是爲了消除原始迷戀,如下所述:http://enterprisecraftsmanship.com/2015/03/07/functional-c-primitive-obsession/

我已閱讀文檔(第144頁):http://stc.sbu.ac.ir/AdminTools/Docs/Files/nhibernate_reference.pdf。它告訴我要引入一種自定義類型。我也讀過這個問題:nHibernate mapping to custom types。我仍然努力做到這一點與NHibernate代碼映射,因此這個問題的原因。

+3

你看過通過組件映射它們嗎(https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping#components)?如果你的數據在同一個表中,這可能是一個更簡單的起點。 –

+0

@David Osbourne,+1 - 該鏈接對行爲非常有幫助。我將Fluent NHibernate的代碼調整爲代碼映射,現在按預期工作(請參閱我的答案)。你能發表一個答案,以便我可以給一些信用? – w0051977

回答

1

你看過映射他們通過components

如果您的數據在同一個表中,與自定義類型相比,這可能是一個更簡單的起點。

+0

供參考組件。 +1。 – w0051977

+0

在我標記你的答案之前。你知道是否有可能將NHibernate字段映射到類構造函數而不是類屬性(我在下面的答案中使用了類屬性)? – w0051977

+0

不確定。如果你看這裏(http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-property),你可以看到可用的訪問策略。它看起來不像構造函數是受支持的。 –

0

繼David Osbournes評論;答案是這樣做的:

Component(x => x.FirstName, y => 
       { 
        y.Property<string>(z => z.FirstName); 
       }); 

NHibernate使用類的FirstName屬性映射到數據庫。