Wednesday, December 29, 2010

Fluent NHibernate AddFromNamespaceOf. The overlooked method of Fluent NHibernate

Unless I'm missing something, writing AddFromNamespaceOf method is a simple undertaking

public static class Helper

    public static FluentMappingsContainer AddFromNamespaceOf<T>(
           this FluentMappingsContainer fmc)
        Type t = typeof(T);
        string ns = t.Namespace;
        var y = from x in t.Assembly.GetTypes()
                    x.FullName == ns + "." + x.Name
                    && x.BaseType.IsGenericType                        
                    && x.BaseType.GetGenericTypeDefinition().IsDerivedFrom(typeof(ClassMap<>))
                select x;
        foreach(Type z in y)
        return fmc;
    private static bool IsDerivedFrom(this Type givenType, Type genericType)
        if (givenType == genericType)
            return true;
        if (givenType.BaseType.IsGenericType)
            return givenType.BaseType
        return false;

Useful when doing unit tests or other kind of testing and don't want to be bothered with creating separate projects/assembly for group of entities. Example:

No comments:

Post a Comment