我有一对多关系的问题。我有以下域类:
public class Installation : Entity<Installation>
{
public virtual string Name { get; set; }
public virtual IList<Institution> Institutions { get; set; }
public Installation()
{
Institutions = new List<Institution>();
}
}
public class Institution : Entity
{
public virtual string Name { get; set; }
public virtual string Address { get; set; }
public virtual string City { get; set; }
public virtual Installation Installation { get; set; }
}
我根据以下帖子制作了实体基类。我定义了以下映射:
public class InstitutionMapping : ClassMap<Institution>
{
public InstitutionMapping()
{
WithTable("Institution");
Id(i => i.Id).GeneratedBy.Guid();
Map(i => i.Name).Not.Nullable().WithLengthOf(50);
Map(i => i.Address).Not.Nullable().WithLengthOf(50);
Map(i => i.City).Not.Nullable().WithLengthOf(50);
References(i => i.Installation).ColumnName("InstallationId").Not.Nullable().WithForeignKey();
}
}
public class InstallationMapping : ClassMap<Installation>
{
public InstallationMapping()
{
WithTable("Installation");
Id(i => i.Id).GeneratedBy.Guid();
Map(i => i.Name).Not.Nullable().WithLengthOf(50);
HasMany<Institution>(i => i.Institutions).KeyColumnNames.Add("InstallationId").Inverse().Cascade.All();
}
}
我通过以下方式对安装添加机构进行单元测试:
Installation installation = TestHelper.CreateAnonymousInstallation();
installation.Institutions.Add(TestHelper.CreateAnonymousInstitution());
installation.Institutions.Add(TestHelper.CreateAnonymousInstitution());
session.Save(installation);
session.Flush();
session.Clear();
Installation returnedInstallation = session.Get<Installation>(installation.Id);
Assert.AreEqual(2, returnedInstallation.Institutions.Count);
我得到一个断言异常,因为返回的机构数为 0。我已经检查了 SQL Profiler,并且机构保存在数据库中,但它们的 InstallationId 为空。有人可以告诉我我做错了什么吗?