是否可以使用 NHibernate 将多个表映射到单个域模型?它基本上是一个UNION,如下所示,但我不确定如何在 C# 中执行域模型和 NHibernate 的映射。
我基本上有1 个抽象类和2 个具体类。每个具体类都可以映射到数据库中的单个表。
SQL 语句:
SELECT *
FROM InCompleOrders
UNION
SELECT *
FROM CompleteOrders
目前我正在这样做:
C# 领域模型:
public enum Status
{
InComplete = 1,
Pending = 2,
Complete = 3
}
public abstract class BaseOrder : Entity
{
public string Property1 {get;set;}
public string Property2 {get;set;}
public string Property3 {get;set;}
public Status Status {get;set;}
public string Reference {get;set;} //this is unique
}
public class InCompleteOrder : BaseOrder
{
public override Status Status
{
get { return Status.InComplete; }
}
}
public class Order : BaseOrder
{
public DateTime DeliveredOn {get;set;}
public DateTime PaidOn {get;set;}
}
数据库表:
InCompleOrders table
InCompleOrderId INT PK
Property1 varchar(255) NULL
Property2 varchar(255) NULL
Property3 varchar(255) NULL
CompleteOrders table
CompleteOrderId INT PK
Status INT
Property1 varchar(255) NOT NULL
Property2 varchar(255) NOT NULL
Property3 varchar(255) NOT NULL
DeliveredOn datetime NOT NULL
PaidOn datetime NOT NULL
NHibernate 映射:
<class name="Order" table="CompleteOrders">
<id name="Id" column="CompleteOrderId" type="int">
<generator class ="hilo"></generator>
</id>
<property name="DeliveredOn" column="DeliveredOn" not-null="true" type="DateTime" />
<property name="PaidOn" column="PaidOn" not-null="true" type="DateTime" />
<property name="Property1" column="Property1" not-null="true" type="string" />
<property name="Property2" column="Property2" not-null="true" type="string" />
<property name="Property3" column="Property3" not-null="true" type="string" />
</class>
<class name="InCompleteOrder " table="InCompleOrders">
<id name="Id" column="InCompleOrderId" type="int">
<generator class ="hilo"></generator>
</id>
<property name="Property1" column="Property1" not-null="false" type="string" />
<property name="Property2" column="Property2" not-null="false" type="string" />
<property name="Property3" column="Property3" not-null="false" type="string" />
</class>
我想避免做类似的事情:
public BaseOrder GetByReference (string reference)
{
BaseOrder bo;
var repoOrder = new Repository<Order>();
bo = repoOrder.FindOne(query);
//query = Restrictions.Eq("Reference", reference)
if (bo == null)
{
var repoInCompOrder = new Repository<InCompleteOrder>();
bo = repoInCompOrder.FindOne(query);
//query = Restrictions.Eq("Reference", reference)
}
return bo;
}
我希望能够执行以下操作:
public Order GetByReference (string reference)
{
var repoOrder = new Repository<Order>();
var bo = repoOrder.FindOne(query);
//query = Restrictions.Eq("Reference", reference) //reference = "abc"
//and this will generate a SQL similar to:
//
//SELECT CompleteOrderId
// , Status
//FROM CompleteOrders
//WHERE Reference = 'abc'
//
//UNION
//
//SELECT InCompleOrderId
// , 1 AS 'Status'
//FROM InCompleOrders
//WHERE Reference = 'abc'
return bo;
}