user24359
user24359

Reputation:

Automatically mapping properties in Fluent NHibernate

I'm taking a complicated legacy schema and mapping it with Fluent NHibernate. The schema is wacky enough that I've given up on automapping; the relationships between tables are weird and complicated, and it would involve a ton of exceptions.

The thing is, the simple properties are totally normal; a table's Title column maps to that entity's Title property, and so on. But because I've opted out of global automapping, there doesn't seem to be a way to avoid mapping each of my string and integer properties on every class. I find myself wanting something like

class SomeMapping : ClassMap<SomeEntity>
{
    public SomeMapping()
    {
        MapEverythingSimple();
    }
}

Before I build something complicated that reflectively emits lambda expressions (or somesuch), am I just missing an obvious feature?

Upvotes: 1

Views: 414

Answers (4)

user24359
user24359

Reputation:

This is not what I ended up doing, but for posterity, here's how you can map properties automatically without using an automapper:

public class PropMap<V> : ClassMap<V>
{
    public PropMap()
    {
        foreach (var propInfo in typeof(V).GetProperties()
            .Where(p => simpleTypes.Contains(p.PropertyType)))
        {
            ParameterExpression param = Expression.Parameter(typeof(V), "x");
            Map(Expression.Lambda<Func<V, object>>(
                Expression.Convert(Expression.MakeMemberAccess(param, propInfo), typeof(object)), param));
        }
    }

    private static readonly Type[] simpleTypes = new[]
    {
        typeof (DateTime),
        typeof (String),
        typeof (int),
        typeof (long),
        typeof (Enum)
    };
}

And then just have the map classes inherit from that. Obviously, it has some serious flaws, and I didn't go with it.

Upvotes: 0

Gareth Hayter
Gareth Hayter

Reputation: 540

Use the trial version of Visual NHibernate to quickly generate your entity classes and Fluent mappings, then take it from there. Disclaimer: I work for Slyce Software.

Upvotes: 0

VahidN
VahidN

Reputation: 19156

Or you can try NHibernate Mapping Generator to generate NHibernate mapping files and corresponding domain classes from existing DB tables: http://nmg.codeplex.com/

Upvotes: 0

Jordan
Jordan

Reputation: 346

How about using automapping and then overrides where things don't fit conventions? I don't think it's too much of a burden. You'll need to specify the complex relationships that don't fit a convention somewhere anyhow.

Upvotes: 1

Related Questions