使用Fluent NHibernate生成Nhibernate数据库

8

我正在尝试使用(新的)Fluent NHibernate(尝试从XML映射文件切换到FNH)。使用下面的代码,我生成了数据库,现在我正在尝试找到相同的解决方案,但使用FNH(我仍然想使用hibernate.cfg.xml):

public void CreateDatabase()
{
    NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();

    cfg.Configure();
    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
    NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

    schema.Create(false, true);
}


namespace MyTestApplication.Entities
{
    public class Person
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    }
}

namespace MyTestApplication.Data.Mapping
{
    public class PersonMapping : ClassMap<Person>
    {
        public PersonMapping()
        {
            Id(x => x.Id);
            Map(x => x.FirstName);
            Map(x => x.LastName);      
        }
    }
}

解决方案

最终,我使用了这个(感谢Marco):

 public void CreationDB()
    {
        FluentConfiguration config = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString("......"))
            .Mappings(
                m => m.FluentMappings.Add(typeof(MyTestApplication.Data.Mapping.PersonMapping)
            ));

        config.ExposeConfiguration(
                  c => new SchemaExport(c).Execute(true, true, false))
             .BuildConfiguration();
    }

1
谢谢!你让我的一天变得美好,并且节省了我数小时的研究时间。 - Fadi Chamieh
1个回答

18

我使用这个方法,尽管我认为你可能会找到更优雅的解决方案:

public FluentConfiguration GetConfig()
{
    return Fluently.Configure()
        .Database(
              MySQLConfiguration.Standard.ConnectionString(
                    c => c.Server("...").Database("...").Username("...").Password("..."))
        )
        .Mappings(
              m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())
        );
}

public void Export(bool script, bool export, bool justDrop)
{
    GetConfig()
         .ExposeConfiguration(
              c => new SchemaExport(c).Execute(script, export, justDrop))
         .BuildConfiguration();
}

最后我调用了Export(true, true, false)函数。


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