Sunday, 1 May 2011

Fluent NHibernate - Ignore Abstract Properties

I was struggling the other day whilst trying to have any property that started with the word "Display" be ignored by Fluent NHiberantes Automap feature. I had it working, but as soon as I added a abstract property to the base class, it all stopped working. I was using the older way of ignoring properties:
using System.Reflection;
using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;

namespace FNHProblem
{
class Program
{
static void Main(string[] args)
{
Fluently .Configure()
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration .MsSql2008.ConnectionString("Server=(local);Integrated Security=SSPI;" ))
.Mappings(mappings => mappings.AutoMappings.Add(AutoMap .Assemblies(Assembly .GetAssembly(typeof (Program )))
.OverrideAll(p => p.IgnoreProperties(ShouldIgnoreMember)))
.ExportTo("." ))
.BuildConfiguration()
.BuildSessionFactory();
}

public static bool ShouldIgnoreMember(Member member)
{
return member.Name.StartsWith("Display");
}
}

public abstract class BaseEntity
{
public virtual int Id { get; set; }

public abstract string DisplayString { get; }
}

public class EntityA : BaseEntity
{
#region Overrides of BaseEntity

public override string DisplayString
{
get { return "I am EntityA"; }
}

#endregion

public virtual string DisplaySomethingElse { get; set; }
}
}

But then switching to using a newer API fixes my problem straight away, so here is the solution:
using  System.Reflection;
using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;

namespace FNHProblem
{
class Program
{
static void Main(string [] args)
{
Fluently .Configure()
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration .MsSql2008.ConnectionString("Server=(local);Integrated Security=SSPI;" ))
.Mappings(mappings => mappings.AutoMappings.Add(AutoMap .Assembly(Assembly .GetAssembly(typeof (Program )), new CustomDefaultAutoMappingConfiguration ()))
.ExportTo("." ))
.BuildConfiguration()
.BuildSessionFactory();
}
}

class CustomDefaultAutoMappingConfiguration : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Member member)
{
if (member.Name.StartsWith("Display" ))
{
return false ;
}
return base .ShouldMap(member);
}
}

public abstract class BaseEntity
{
public virtual int Id { get ; set ; }

public abstract string DisplayIShouldBeIgnored { get ; }
}

public class EntityA : BaseEntity
{
public override string DisplayIShouldBeIgnored
{
get { return "I am EntityA" ; }
}
}
}

Submit this story to DotNetKicks Shout it