[英]NHibernate code mapping bag join two tables
I have the following definition for a Transaction (as in purchase details) object : 我对交易对象(如购买明细)具有以下定义:
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))));
}
}
And TransactionProduct is defined like this : 而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"));
}
}
Now, I want to select a transaction and populate the Products array in a single select (I know I can select the transaction then the products but It's bad practice) 现在,我想选择一个事务,然后一次选择即可填充Products数组(我知道我可以先选择事务,然后再选择产品,但这是不好的做法)
So I'm using this : 所以我正在使用这个:
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();
}
This work's quite well but the problem is that if I have a transaction with 2 products, I get 2 transaction objects with 2 products inside them, same goes for if I have a transaction with 4 products, I get 4 transaction objects with 4 products. 这项工作做得很好,但是问题是,如果我有2个产品的交易,我得到2个带有2个产品的交易对象,如果我有4个产品的交易,同样得到4个产品4个交易对象。 The transaction objects are good, but the problem is the duplicates. 事务对象很好,但是问题是重复的。
I can probably solve it with Distinct() but again, I want best practice 我可能可以用Distinct()来解决它,但是我还是要最佳实践
我在Where(...)
之后使用.TransformUsing(Transformers.DistinctRootEntity)
解决了它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.