我知道这个问题已经以类似的形式多次提出,但没有一个线程可以给我问题的具体答案。
我使用 Fluent 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; }
}
如果有人终于能帮助我,我会非常高兴!我已输入 Google 返回页面的所有可能的搜索字符串,标记为已访问...
谢谢,
阿恩
编辑:已更改标题...想要允许单个属性NULL
最佳答案
创建属性:
[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<>)));
}
}
将该属性拖放到您的属性之上。
关于fluent-nhibernate - Fluent NHibernate - 自动映射 : allow null for single properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4097578/