views:

36

answers:

3

Hi all. 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 : 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; }
}

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.

A: 

Im guessing you are trying to save an article, (you specified inverse) therefore you need this: Article.Category = category;

Kelly
A: 

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;
Michael Shimmins
A: 

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?

Rich