2011-10-17 34 views
8

我正在嘗試使用(新)Fluent NHibernate(嘗試從XML映射文件切換到FNH)。用下面的代碼,我生成的數據庫,我試圖找到相同的解決方案,但與FNH(我想還是用hibernate.cfg.xml中):用Nhibernate使用流利NHibernate生成數據庫

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);  
     } 
    } 
} 

解決方案

最後,我用這個(感謝馬爾科):

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

謝謝!你創造了我的一天,爲我節省了數小時的研究 –

回答

17

我用這個,即使我認爲你可以找到更優雅:

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)