2010-11-04 42 views
2

我知道这个问题已经以类似的形式多次提出,但是没有一个线程可以给我具体的答案给我的问题。Fluent NHibernate - automapping:允许单个属性为空

我使用流利的NHibernate和Fluent的自动映射来映射我的域实体。现在,我使用这种约定类设置的所有属性NOT NULL

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

的一大问题是:

什么我需要做的,让我的实体类的单一性质是NULL

这里是我的实体类中的一种:

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

我倒是真的很高兴,如果有人可以帮助最终我出去!我已经进入到谷歌的回报网页上的所有可能的搜索字符串,标记为已经访问过...

谢谢
阿恩

编辑:改标题...希望允许NULL单性

回答

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

将属性放在属性上。

+0

感谢您回答Mathieu!我会尝试你的方法! “typeof(Nullable <>)是什么意思?我不需要标记单个属性?使用你的方法,允许哪些属性不为空,字符串? – dasnervtdoch 2010-11-05 08:26:31

+0

@dasnervtdoch你把属性放在你想要的属性上标记为可空。 – mathieu 2011-05-19 11:48:19