这是一个很好的演练,可以帮助您启动和运行:http ://dotnetslackers.com/articles/ado_net/Your-very-first-NHibernate-application-Part-1.aspx
您的映射看起来像这样。请注意,我对您希望如何生成身份以及这些实体之间的映射类型进行了一些假设。
public class User
{
public int ID { get; set; }
public string Username { get; set; }
public MoreDetails ExtendedDetails { get; set; }
}
public class MoreDetails
{
public int ID { get; set; }
public string Firstname { get; set; }
public User User { get; set; } // Foreign key in the DB
}
public UserMapping()
{
Not.LazyLoad();
Id(e => e.ID).GeneratedBy.Identity();
Map(e => e.Username).Not.Nullable();
HasOne(x => x.ExtendedDetails)
.Cascade
.SaveUpdate();
}
public MoreDetailsMapping()
{
Not.LazyLoad();
Id(e => e.ID).GeneratedBy.Identity();
Map(e => e.Firstname).Not.Nullable();
References(x => x.User).Column("UserID");
}
为了查询您的关系数据,您需要在 nhibernate 中打开一个会话。我通常按照这个思路创建一个助手。
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
InitializeSessionFactory();
return _sessionFactory;
}
}
private static void InitializeSessionFactory()
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(@"Server=localhost\SQLExpress;Database=SomeDB;Trusted_Connection=True;")
.ShowSql()
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<User>())
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
从那里你可以像这样直接查询:
public IQueryable<User> Users
{
get { return NHibernateHelper.OpenSession().Query<User>(); }
}
请注意,我在这里留下了很多内容,但希望这将有助于您启动和运行。