简而言之:查询“父母”表结果“父母”+来自“孩子”的记录。“孩子”对“父母”有 FK,因此我的重复项与“孩子”中的 FK 数量一样多。我在 ASP.NET MVC3 项目中使用 Fluent.NHibernate。
所以,DB看起来像这样
TABLE parents
***id
***system_name
TABLE children
***id
***custom_name
***parent_id
FK: parent_id === "FK_parent_id_to_id_in_parents"
模型:
public class Parent
{
public virtual int Id { get; set; }
public virtual string SystemName { get; set; }
}
public class Child: Parent
{
public override int Id
{
get
{
return base.Id;
}
set
{
base.Id = value;
}
}
public virtual string CustomName
{
get
{
return _CustomName != null ? _CustomName : base.SystemName;
}
set
{
_CustomName = value;
}
}
public virtual Parent ParentId { get; set; }
private string _CustomName = string.Empty;
}
映射:
public class ParentMapper: ClassMap<Parent>
{
Table("parents");
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.SystemName, "system_name").Not.Nullable();
}
public class ChildMapper: ClassMap<Child>
{
Table("children");
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.DisplayName, "display_name");
References(x => x.ParentId).Column("parent_id").Cascade.None().ForeignKey("FK_parent_id_to_id_in_parents");
}
询问:
using(ITransaction tr = session.BeginTransaction())
{
List<Parent> lp = new List<Parent>(session.CreateCriteria(typeof(Parent)).List<Parent>());
tr.Commit();
}