开发者

Automatically mapping properties in Fluent NHibernate

开发者 https://www.devze.com 2023-03-10 01:48 出处:网络
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

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?


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号