NHibernate代码映射包连接两个表
本文关键字:两个 代码 映射 包连接 NHibernate 连接 | 更新日期: 2023-09-27 18:21:47
我对交易(如购买详细信息)对象有以下定义:
public class Transaction : MappingObject
{
public virtual int Id { get; set; }
public virtual IList<TransactionProduct> Products { get; set; }
}
public class TransactionMap : ClassMapping<Transaction>
{
public TransactionMap()
{
Table("TRANSACTIONS_TBL");
Id(x => x.Id, m =>
{
m.Column("ID");
m.Generator(Generators.Identity);
});
Bag(x => x.Products, m =>
{
m.Inverse(true);
m.Table("TRANSACTION_PRODUCTS_TBL");
m.Key(k => k.Column("TRANSACTION_ID"));
m.Lazy(CollectionLazy.NoLazy);
},
relation => relation.OneToMany(mapper => mapper.Class(typeof(TransactionProduct))));
}
}
TransactionProduct的定义如下:
public class TransactionProduct : MappingObject
{
public virtual int TransactionId { get; set; }
public virtual int ProductId { get; set; }
public virtual int Quantity { get; set; }
public override bool Equals(object obj)
{
var t = obj as TransactionProduct;
if (t == null)
return false;
if (TransactionId == t.TransactionId && ProductId == t.ProductId)
return true;
return false;
}
public override int GetHashCode()
{
return (TransactionId + "|" + ProductId).GetHashCode();
}
}
public class TransactionProductMap : ClassMapping<TransactionProduct>
{
public TransactionProductMap()
{
Table("TRANSACTION_PRODUCTS_TBL");
ComposedId(map =>
{
map.Property(x => x.TransactionId, m => m.Column("TRANSACTION_ID"));
map.Property(x => x.ProductId, m => m.Column("PRODUCT_ID"));
});
Property(x => x.Quantity, m => m.Column("QUANTITY"));
}
}
现在,我想选择一个交易,并在一次选择中填充Products数组(我知道我可以先选择交易,然后选择产品,但这是不好的做法)
所以我用这个:
using (var session = CommonDAL.GetSession())
{
Transaction transactionAlias = null;
TransactionProduct transactionProductAlias = null;
return session.QueryOver(() => transactionAlias).
JoinAlias(() => transactionAlias.Products, () => transactionProductAlias).
Where(() => transactionAlias.Id == transactionProductAlias.TransactionId).List().ToList();
}
这项工作做得很好,但问题是,如果我有一个有2个产品的交易,我会得到2个里面有2个商品的交易对象,同样的情况也适用于如果我有4个产品的事务,我会有4个有4个商品的事务对象。事务对象是好的,但问题是重复。
我可能可以用Distinct()来解决它,但同样,我想要最佳实践
在Where(...)
之后,我使用.TransformUsing(Transformers.DistinctRootEntity)
解决了它