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

4

1 回答 1

4

创建一个属性:

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

和一个约定:

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<>)));
    }
}

将属性放在您的属性之上。

于 2010-11-04T14:36:02.123 回答