NHibernate Fluent 添加外部程序集映射



我有一个项目,我的映射和实体存储在另一个项目中的其他类库和NHibernate层中。在我的测试项目中,我想通过流畅的配置来添加这些映射......映射。。。通过 assebly 而不是单独。 在下面的代码中,您可以看到我只添加了一个实体。但我想配置它以扫描我的其他程序集。 我敢肯定我只是错过了这里显而易见的..任何指示将不胜感激...

 [Test]
    public void Can_generate_schemaFluently()
    {
        var cfg = new Configuration();  
        cfg.Configure();
        Configuration configuration = null;
        ISessionFactory SessionFactory = null;
        ISession session = null;
        SessionFactory = Fluently.Configure(cfg)
            *** WOULD LIKE TO ADD MY ASSEBLIES and autoscan for objects instead ***
          .Mappings(m => m.FluentMappings
                        .Add(typeof(StudentEOMap))
                  )
           .ExposeConfiguration(x => configuration = x)
            .BuildSessionFactory();
        session = SessionFactory.OpenSession();
        object id;
        using (var tx = session.BeginTransaction())
        {
            var result = session.Get<StudentEO>(1541057);
            tx.Commit();
            Assert.AreEqual(result.StudId, 1541057);
        }
        session.Close();
    }

自动映射

如果要按类型进行筛选,可以使用IAutomappingConfiguration并从DefaultAutomappingConfiguration派生,如下所示:

public class StandardConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Type type)
    {
        // Entity is the base type of all entities
        return typeof(Entity).IsAssignableFrom(type);
    }
}

如果不需要筛选,也可以使用 DefaultAutomappingConfiguration。但我的进一步示例使用 StandardConfiguration.

像这样更改您的配置,以将您的类型填充到 FluentNHibernate:

SessionFactory = Fluently.Configure(cfg)
    .Mappings(m => MapMyTypes(m))
    .ExposeConfiguration(x => configuration = x)
    .BuildSessionFactory();

MapMyTypes方法应如下所示:

private void MapMyTypes(MappingConfiguration m)
{
    m.AutoMappings.Add(AutoMap.Assemblies(new StandardConfiguration(), 
        Assembly.GetAssembly(typeof(Entity)), 
        Assembly.GetAssembly(typeof(OtherAssemblyEntity)))
    );
}

您可以添加多个程序集,所有程序集都通过 StandardConfiguration 进行过滤。

编辑

FluentMappings

看来我误读了你的问题。要添加映射,您可以使用类似的方法来实现这一目标,但没有IAutomappingConfiguration。只需将MapMyTypes方法更改为:

private void MapMyTypes(MappingConfiguration m)
{
    m.FluentMappings.AddFromAssembly(Assembly.GetAssembly(typeof(EntityMap)));
}

您还可以像这样组合 FluentMapping 和 AutoMapping:

private Action<MappingConfiguration> MapMyTypes()
{
    return m =>
    {
        MapFluent(m);
        MapAuto(m);
    };
}

最新更新