Search code examples
fluent-nhibernateconventions

Fluent NHibernte Alterations / Conventions


I like the pattern I saw in this blog post (http://marekblotny.blogspot.com/2009/04/conventions-after-rewrite.html), where the author is checking to see if a table name alteration has already been made before applying a convention.

public bool Accept(IClassMap target)
{
    //apply this convention if table wasn't specified with WithTable(..) method
    return string.IsNullOrEmpty(target.TableName);
}

The convention interface I'm using for a string length is IProperty:

public class DefaultStringLengthConvention: IPropertyConvention
{
    public bool Accept(IProperty property) {
        //apply if the string length hasn't been already been specified
        return ??; <------ ??
    }

    public void Apply(IProperty property) {
        property.WithLengthOf(50);
    }
}

I don't see where IProperty exposes anything that tells me if the property has already been set. Is this possible?

TIA, Berryl


Solution

  • To clarify in code what Stuart and Jamie are saying, here's what works:

    public class UserMap : IAutoMappingOverride<User>
    {
        public void Override(AutoMap<User> mapping) {
            ...
            const int emailStringLength = 30;
            mapping.Map(x => x.Email)
                .WithLengthOf(emailStringLength)                        // actually set it
                .SetAttribute("length", emailStringLength.ToString());  // flag it is set
            ...
    
        }
    }
    
    public class DefaultStringLengthConvention: IPropertyConvention
    {
        public bool Accept(IProperty property) {
            return true;
        }
    
        public void Apply(IProperty property) {
            // only for strings
            if (!property.PropertyType.Equals(typeof(string))) return;
    
            // only if not already set
            if (property.HasAttribute("length")) return;
    
            property.WithLengthOf(50);
        }
    }