【发布时间】:2015-07-24 08:47:51
【问题描述】:
我是 NHibernate 的新手,我正在创建一个简单的场景来测试框架功能。
我必须要基本实体:
public class School : BaseEntity
{
public virtual string Code { get; set; }
public virtual string Name { get; set; }
}
public class Student : BaseEntity
{
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
public virtual string Email { get; set; }
public virtual School School { get; set; }
}
从一个简单的基类继承:
public abstract class BaseEntity
{
public virtual int Id { get; protected set; }
}
比我这样使用 FluentNhibernate 映射实体:
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2012.ConnectionString(
c => c.FromConnectionStringWithKey("DataModel")))
.Mappings(m => m.AutoMappings
.Add(AutoMap.AssemblyOf<BaseEntity>()
.Where(t => t.Namespace == "MyApp.Models"))
.IgnoreBase<BaseEntity>()
.Override<User>(map =>
{
map.Table("Users");
map.HasOne<School>(u => u.School).ForeignKey("SchoolId");
})
.Override<School>(map =>
{
map.Table("Schools");
})
))
.BuildSessionFactory();
我的测试代码很简单:
using (var transaction = DbSession.BeginTransaction())
{
Student u1 = DbSession.Get<Student>("user-id");
School s1 = DbSession.Get<School>("school-id");
u1.School = s1; // updating the associated school
DbSession.SaveOrUpdate(u1);
transaction.Commit(); // !!! the foreign key is not updated
}
检查学生表,该行未使用新的学校 ID 更新。
那么,我的代码有什么问题?我的映射中是否存在不正确(或缺失)的内容?
【问题讨论】:
标签: c# nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping