我是新的nhibernte,我真的很接近我的头撞石头。笑话放在一边;我正在尝试一个简单的一对多关联。
我有两个班书和章。一本书可能包含一个以上的章节。当我向配置添加程序集时,它给出了重复错误。当我这次删除它时,它会抛出一个没有持久性错误。我真的被卡住了。请帮帮....
我的代码和hbm文件是这样的。
类:
public class Book
{
public virtual Guid Id { get; set; }
public virtual string Title { get; set; }
public virtual string Author { get; set; }
public virtual IList<Chapter> Chapters { get; set; }
}
public class Chapter
{
public virtual Guid Id { get; set; }
public virtual string Title { get; set; }
public virtual string Notes { get; set; }
}
CODE:
private void Form1_Load(object sender, EventArgs e)
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
LoadNHibernateCfg();
using (ISession session = sessionFactory.OpenSession())
{
using (ITransaction tx = session.BeginTransaction())
{
Book cookbook = new Book()
{
Title = "NHibernate Cookbook",
Author = "Jason Dentler",
Chapters = new List<Chapter>() {
new Chapter() { Title = "Models and Mappings" },
new Chapter() { Title = "Configuration and Schema" },
new Chapter() { Title = "Sessions and Transactions" }
}
};
session.Save(cookbook);
tx.Commit();
session.Close();
}
}
}
public static void LoadNHibernateCfg()
{
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Book).Assembly); //____This Lines
cfg.AddAssembly(typeof(Chapter).Assembly); //____This Lines
new SchemaExport(cfg).Execute(true, true, false);
}
Book and chapter hbm.xml文件
<class name="Book" table="Books">
<id name="Id">
<generator class="guid.comb" />
</id>
<property name="Title" not-null="true" />
<property name="Author" not-null="true"/>
<list name="Chapters" cascade="all-delete-orphan">
<key column="BookId"/>
<index column="ChapterIndex"/>
<one-to-many class="Chapter"/>
</list>
</class>
<class name="Chapter" table="Chapters">
<id name="Id">
<generator class="guid.comb" />
</id>
<property name="Title" not-null="true" />
<property name="Notes" />
</class>
</class>
我的配置文件。
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="query.substitutions">hqlFunction=SQLFUNC</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=BEN-PC\SQLEXPRESS;Initial Catalog=movieMng;Integrated Security=True</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
提前感谢您的帮助。
答案 0 :(得分:0)
您只应添加其中一个:
public static void LoadNHibernateCfg()
{
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Book).Assembly); //____This Lines
new SchemaExport(cfg).Execute(true, true, false);
}