I have a table http://img36.imageshack.us/i/beztytuuszxq.png/ and mapping:
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);
}
}
The entity looks that:
public class Category : Enti开发者_运维技巧tyBase
{
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; }
}
When I want to save an Category object to db, when Parent property is set to null, I have exception:
not-null property references a null or transient value CMS.Domain.Entities.Article.Category
I cannot change the
public virtual Category Parent { set; get; }
line to
public virtual Category? Parent { set; get; }
or
public virtual Nullable<Category> Parent { set; get; }
because I have an error during compile:
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>'
I don't know what to change to have possibility to save Category objects without parents.
You can't make a reference type Nullable (as it already is). Nullable<T>
(or T?
) can only be used with a non-nullable value type (such as int
or DateTime
).
The error refers to CMS.Domain.Entities.Article.Category - the Category property in the Article class. You haven't provided the map file for the Article entity, however I assume it maps the Category property and either specifies Not.Nullable()
or doesn't specific Nullable()
.
If the domain model allows for the Article entity to contain a null Category use Nullable()
otherwise you need to set the category when creating/saving the Article:
Article.Category = aCategory;
The reason you can't Nullable the Category is because Nullable is only meant for value types, and Category, by definition, is a reference type and therefore already can support nulls on properties defined as Category. Can you provide a full stack trace of the exception?
Im guessing you are trying to save an article, (you specified inverse) therefore you need this: Article.Category = category;
精彩评论