从Fluent NHibernate生成XML映射

17

如何在MappingIntegrationTests中作为测试的一部分生成XML映射文件?

我需要手动检查流畅映射是否与遗留项目中的映射相对应。

3个回答

19
您可以像这样做:
 config.Mappings(m => 
    {
        m.FluentMappings.ExportTo("...file path here...");
        m.HbmMappings.ExportTo("...file path here...");
        m.AutoMappings.ExportTo("...file path here...");
    {
);

我个人不喜欢它。如果我找到更好的方法(如果有的话),我会更新答案。
请参见
http://blog.jagregory.com/2009/02/03/fluent-nhibernate-configuring-your-application/
或者如果链接已损坏,请参见以下内容
https://github.com/jagregory/fluent-nhibernate/wiki/Database-configuration

至少在当前版本的FluentNH(例如1.3),m.HbmMappings.ExportTo()不存在 - 这是有道理的,因为.hbm映射已经是文件了。 - Oliver
链接已损坏。 - Owen Pauling
嗯,是的。自2009年以来已经有8年了吧。我添加了另一个类似的链接。 - Meligy
文件的扩展名是什么? - nix86

8
您可以通过调用ExportTo()方法来生成XML映射。
例如:
ISessionFactory sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
  .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
    .ConnectionString(connectionString)
  )
  .Mappings(m => m.FluentMappings.AddFromAssembly(assembly)
    .ExportTo(@"C:\your\export\path")
  )
  .BuildSessionFactory();

文档请参见:

http://wiki.fluentnhibernate.org/Fluent_configuration


链接已损坏。 - Owen Pauling

3

我使用(几乎)这个扩展方法来获取内存中的xbm,以便在我的测试项目中查看:

   public static IDictionary<string, string> LoadHBM(this FluentConfiguration cfg)
    {
        var result = new Dictionary<string, string>();
        var mem = new MemoryStream();
        var writer = new StreamWriter(mem);
        var reader = new StreamReader(mem);

        cfg.Mappings(x =>
        {
            x.FluentMappings.ExportTo(writer);
            x.AutoMappings.ExportTo(writer);
        });

        cfg.BuildConfiguration();
        writer.Flush();
        mem.Seek(0, 0);
        var hbm = reader.ReadToEnd();

        var objects = XElement.Parse("<junk>" + hbm + "</junk>").Elements();
        objects.ToList().ForEach(x => result.Add(x.Elements().First().Attribute("name").Value, x.ToString()));
        return result;
    }

编辑:更新至FNH 1.2版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接