I define a simple Bug Class:
using System;
namespace BugNS.Entities
{
class Bug
{
public virtual int Id { get; private set; }
public virtual int BugNumber { get; set; }
}
}
and a simple mapper class:
using System;
using FluentNHibernate.Mapping;
using BugNS.Entities;
namespace BugNS.Mappings
{
class BugMap : ClassMap<Bug>
{
public BugMap()
{
Id(b => b.Id);
Map(b => b.BugNumber);
}
}
}
and then just try to use it like:
using System;
using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using BugNS.Entities;
namespace BugNS
{
class Program
{
private const string DbFile = "bugs.db";
static void Main()
{
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
Bug b = new Bug { BugNumber = 121212 };
session.SaveOrUpdate(b);
transaction.Commit();
}
}
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard
.UsingFile(DbFile))
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Program>())
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
private static void BuildSchema(Configuration config)
{
// delete the existing db on each run
if (File.Exists(DbFile))
File.Delete(DbFile);
// this NHibernate tool takes a configuration (with mapping info in)
// and exports a database schema from it
new SchemaExport(config)
.Create(false, true);
}
}
}
and I got the following error:
An unhandled exception of type 'NHibernate.MappingException' occurred in NHibernate.dll
Additional information: No persister for: BugNS.Entities.Bug
I am sorry, but I just started learning Fluent and NHibernate from the docs. It would be great if someone knows the solution to this issue, as I already spend many hours in vain.
Access level of the class needs to be public for Fluent to make use of it.
Try the following:
public class Bug
{
public virtual int Id { get; private set; }
public virtual int BugNumber { get; set; }
}
public class BugMap : ClassMap<Bug>
{
public BugMap()
{
Id(b => b.Id);
Map(b => b.BugNumber);
}
}
This is a gotcha for me as well when I started using Fluent.
One more thing that generally goes wrong is missing out virtual
keyword, which is needed for NHibernate to make changes to those properties. Its nice that you made that part correct :)
Hope that helps.
Thanks
You need to make the Bug and BugMap classes public so that NHibernate/Fluent NHibernate can see them.
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