2010-09-21 78 views
0

我有一個表http://img36.imageshack.us/i/beztytuuszxq.png/和映射:的NHibernate +流暢+映射

public class CategoryMap : ClassMap<Category> 
{ 
    public CategoryMap() 
    { 
     Table(FieldNames.Category.Table); 
     Id(x => x.ID); 
     Map(x => x.Name).Not.Nullable(); 
     Map(x => x.ShowInMenuBar).Not.Nullable(); 
     References(x => x.Parent).Column(FieldNames.Category.ID).Nullable(); 
     HasMany(x => x.Articles).Cascade.All().Inverse().Table(FieldNames.Article.Table); 
    } 
} 

實體看起來是:

public class Category : EntityBase 
{ 
    public virtual int ID { set; get; } 
    public virtual string Name { set; get; } 
    public virtual Category Parent { set; get; } 
    public virtual bool ShowInMenuBar { set; get; } 
    public virtual IList<Article> Articles { set; get; } 
} 

當我要救一個類別對象數據庫,當parent屬性設置爲空,我有例外:

not-null property references a null or transient value CMS.Domain.Entities.Article.Category

我不能

public virtual Category Parent { set; get; } 

線改爲

public virtual Category? Parent { set; get; } 

public virtual Nullable<Category> Parent { set; get; } 

,因爲我在編譯過程有一個錯誤:

CMS.Domain.Entities.Category' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

我不知道如何改變以便有可能在沒有父母的情況下保存Category對象。

回答

1

你不能使一個引用類型爲空(因爲它已經是)。 Nullable<T>(或T?)只能與非空值類型(例如intDateTime)一起使用。

錯誤指的是CMS.Domain.Entities.Article.Category - Article類中的Category屬性。您尚未提供Article實體的映射文件,但我認爲它映射了Category屬性,並指定Not.Nullable()或不具體Nullable()

如果域模型允許條實體包含空類別使用Nullable()否則你需要設置的類別創建/保存文章的時候:

Article.Category = aCategory; 
0

我猜你試圖保存一篇文章,(你指定爲inverse),因此你需要這個: Article.Category = category;

1

你不能爲空類別的原因是因爲Nullable僅用於值類型,根據定義,Category是引用類型,因此已經可以在定義爲Category的屬性上支持空值。你能否提供異常的完整堆棧跟蹤?