2

I know this question has been raised in similar form multiple times, but none of the threads could give me the concrete answer to my question.

I use Fluent NHibernate and Fluent`s auto-mapping to map my domain entities. Right now, I use this convention class to set all properties NOT NULL:

public class NotNullColumnConvention : IPropertyConvention
{
    public void Apply(FluentNHibernate.Conventions.Instances.IPropertyInstance instance)
    {
        instance.Not.Nullable();
    }
} 

The big question is:

What do I need to do, to allow single properties of my entity classes to be NULL?

Here is one of my entity classes:

public class Employee : Entity
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

I´d be really pleased, if someone can finally help me out! All possible search string I have entered into Google return pages, marked as already visited...

Thanks,
Arne

EDIT: Changed title ... Want to allow NULL for single properties

abedurftig
  • 1,118
  • 1
  • 12
  • 24

1 Answers1

4

Create an attribute :

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class CanBeNullAttribute : Attribute
{
}

And a convention :

public class CanBeNullPropertyConvention : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(
            x => !this.IsNullableProperty(x)
            || x.Property.MemberInfo.GetCustomAttributes(typeof(CanBeNullAttribute), true).Length > 0);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Nullable();
    }

    private bool IsNullableProperty(IExposedThroughPropertyInspector target)
    {
        var type = target.Property.PropertyType;

        return type.Equals(typeof(string)) || (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }
}

Drop the attribute on top of your properties.

mathieu
  • 30,974
  • 4
  • 64
  • 90
  • Thanks for you answer Mathieu! I shall try your approach! What does "typeof(Nullable<>) mean? And I don´t have to mark single properties? Using your approach, which properties are allowed to be not null, Strings? – abedurftig Nov 05 '10 at 08:26
  • @dasnervtdoch you put the attribute on the properties you want to mark as nullable. – mathieu May 19 '11 at 11:48