I'm trying to use (new with) Fluent NHibernate (trying to switch from XML mapping file to FNH). With the code below, I generated the database, I'm trying to find the same solution but with FNH (I'd like still use 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);
}
}
}
Solution
Finally, I use this (Thanks to 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();
}
Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
Difference between NHibernate and Entity FrameworkEntity framework requires additional connections to handle databases other than MSSQL, which nHibernate provides. In terms of data loading, SQL generation, custom column types, custom collections, and so on, NHibernate can be modified.
NHibernate is Designed to serve as a persistence layer exclusively for the . Net framework based on Object-Relational Mapping Technique. A tool that creates a "virtual representation" of database objects within the code. Used to solve the problem of impedance mismatch between Class and relational databases and tables.
I use this, even if I think you could find something more elegant:
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();
}
Finally I call Export(true, true, false)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With