Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Nhibernate Automap convention for not-null field

Could some one help, how would I instruct automap to have not-null for a column?

public class Paper : Entity
{
    public Paper() { }

            [DomainSignature]
            [NotNull, NotEmpty]
            public virtual string ReferenceNumber { get; set; }

            [NotNull]
            public virtual Int32 SessionWeek { get; set; }
}

But I am getting the following:

 <column name="SessionWeek"/>

I know it can be done using fluent-map. but i would like to know it in auto-mapping way.

like image 658
Robi Avatar asked Apr 09 '10 08:04

Robi


3 Answers

Thank you. Also, for reference properties ReferenceConvention need to be done. This is the code that works:

public class ColumnNullConvention : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        if (instance.Property.MemberInfo.IsDefined(typeof(NotNullAttribute), false))
            instance.Not.Nullable();
    }

}  public class ReferenceConvention : IReferenceConvention
{
    public void Apply(FluentNHibernate.Conventions.Instances.IManyToOneInstance instance)
    {
        instance.Column(instance.Property.Name + "Fk");


        if (instance.Property.MemberInfo.IsDefined(typeof(NotNullAttribute), false))
            instance.Not.Nullable();

    }
}
like image 177
Robi Avatar answered Nov 05 '22 11:11

Robi


Here is the way I do it, basically taken from the link you see in the code. There are some other useful conventions there as well

HTH,
Berryl

/// <summary>
/// If nullability for the column has not been specified explicitly to allow NULL, then set to “NOT NULL”.
/// </summary>
/// <remarks>see http://marcinobel.com/index.php/fluent-nhibernate-conventions-examples/</remarks>
public class ColumnNullabilityConvention : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Nullable, Is.Not.Set);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Not.Nullable();
    }
}
like image 41
Berryl Avatar answered Nov 05 '22 12:11

Berryl


If you are mostly happy with Automapping results but occasionally need to override it for say a couple of properties in a class I find implementing a IAutoMappingOverride for that class the easiest way to achieve that:

public class UserMappingOverride : IAutoMappingOverride<User>
{
      public void Override(AutoMapping<User> mapping)
      {
          mapping.Map(x => x.UserName).Column("User").Length(100).Not.Nullable();
      }
}

And then use them like this:

AutoMap.AssemblyOf<User>().UseOverridesFromAssemblyOf<UserMappingOverride>();

Similar to ClassMaps - but you don't need to describe every field in the class. This approach is very similar to the Entity Framework's Code First Fluent API way.

like image 20
Zar Shardan Avatar answered Nov 05 '22 11:11

Zar Shardan