使用Fluent NHibernate使用Nhibernate生成数据库

时间:2011-10-17 11:29:34

标签: database nhibernate configuration fluent-nhibernate

我正在尝试使用(新的)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 个答案:

答案 0 :(得分: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)