通过Id将实体映射到自联接表

时间:2013-10-02 12:20:52

标签: nhibernate nhibernate-mapping nhibernate-criteria

我的旧表“AllData”包含以下列:Id, Title, LookupColumn1Id 我的实体:

public class BaseEntity
{ 
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}
public class Employee: BaseEntity
{ 
    public virtual int DepartmentId { get; set; }
    public virtual string DepartmentName { get; set; }
}
public class Department: BaseEntity
{
    public virtual int HeadManagerId { get; set; }
}

我想像这样生成SELECT:

SELECT EmployeeTable.Title, DepartmentTable.Id, DepartmentTable.Title
FROM AllData EmployeeTable left outer join AllData DepartmentTable on EmployeeTable.LookupColumn1Id=DepartmentTable.Id       
WHERE EmployeeTable.tp_ListId = @p0 and (DepartmentTable.Title = @p1)       

1 个答案:

答案 0 :(得分:0)

让我告诉你,其中一个选择。对于这个草案,我希望,具有LookupColumn1Id NULL的记录将扮演Department的角色,其余的将扮演Employee的角色。

实体可能如下所示:

public class BaseEntity
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; } 
}
public class Employee : BaseEntity
{
    public virtual Department Department { get; set; } // to lookup record
}
public class Department : BaseEntity
{
    public virtual IList<Employee> Employees { get; set; } // the way back 
}

映射可能是这样的:

<class name="Department" table="[dbo].[AllData]" lazy="true" batch-size="25" 
    where="LookupColumn1Id IS NULL" >
  <id name="Id" column="Id" generator="native" />

  <property not-null="true"  name="Name" column="Title" />

  <bag name="Employees" >
    <key column="LookupColumn1Id" />
    <one-to-many class="Employee"/>
  </bag>

</class>

<class name="Employee1" table="[dbo].[AllData]" lazy="true" batch-size="25"
  where="LookupColumn1Id IS NOT NULL" >
  <id name="Id" column="Id" generator="native" />

  <property not-null="true"  name="Name" column="Title" />

  <many-to-one name="Department" class="Department" column="LookupColumn1Id " />
</class>

此映射用于读取访问(所需的SELECT)正在运行。现在,我们可以创建一个查询:

[TestMethod]
public void TestAllData()
{
    var session = NHSession.GetCurrent();

    // the Employee Criteria
    var criteria = session.CreateCriteria<Employee>();
    // joined with the Department
    var deptCrit = criteria.CreateCriteria("Department", JoinType.LeftOuterJoin);

    // here we can filter Department
    deptCrit.Add(Restrictions.Eq("Name", "Dep Name"));
    // here we can filter Employee
    criteria.Add(Restrictions.Eq("Name", "Emp Name"));


    // the SELECT
    var results = criteria
        .List<Employee>();

    Assert.IsTrue(results.IsNotEmpty());

    var employee = results.First();

    // check if all data are injected into our properties
    Assert.IsTrue(employee.Name.IsNotEmpty());
    Assert.IsTrue(employee.Department.Name.IsNotEmpty());
}

这种情况一般都有效,但我们所做的只是C#中的继承(都来自BaseEntity),而不是映射。

原因是,缺少列将扮演Discriminator角色。这就是为什么我们使用带有WHERE属性的映射(请参阅xml中的类元素),通过查找列存在来区分DepartmentEmployee