我想使用FN在表之间建立联接。 但我得到的输出结果并不完全正确。 我的代码:
public class Store
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; protected set; }
public virtual IList<Employee> Staff { get; protected set; }
public virtual string FirstName { get; set; }
}
public StoreMap()
{
Table("store");
Id(store => store.Id).Column("id").GeneratedBy.Increment();
Map(store => store.Name).Column("name");
Join("employee", m =>
{
m.Optional();
m.KeyColumn("store_id");
m.Map(x => x.FirstName).Column("first_name");
});
}
var shops = session.QueryOver<Store>().Where(shop => shop.Id == 1).List();
生成的SQL查询
SELECT this_.id as id3_0_,
this_.name as name3_0_,
this_1_.first_name as first2_0_0_
FROM store this_
left outer join employee
this_1_ on this_.id=this_1_.store_id
WHERE this_.id == 1
如果我只是执行此SQL查询,我会以
的形式获得正确的结果id3_0_ name3_0_ first2_0_0_
1 Bargin Basin Daisy
1 Bargin Basin Jack
1 Bargin Basin Sue
但如果我通过FN做,那么变量商店我得到以下数组:
1 Bargin Basin Daisy
1 Bargin Basin Daisy
1 Bargin Basin Daisy
我使用的是FN版本2.0.1.0,NHibernate 4.0。感谢。
答案 0 :(得分:2)
Join(...)
用于一对一关联,但是你有一对多的Employee,所以连接每个商店返回多一行,NHibernate总是看到相同的Id告诉他是同一个对象,因此它给你2次相同的参考。
您可能想要的是员工对其商店的预测
class EmploymentDto
{
public int StoreId { get; set; }
public string StoreName { get; set; }
public string FirstName { get; set; }
}
EmploymentDto dto = null;
Employee employee = null;
var employments = session.QueryOver<Store>()
.Where(shop => shop.Id == 1)
.JoinAlias(s => s.Staff, () => employee)
.SelectList(l =>
l.Select(s => s.Id).WithAlias(() => dto.StoreId)
l.Select(s => s.Name).WithAlias(() => dto.StoreName)
l.Select(() => employee.FirstName).WithAlias(() => dto.FirstName)
.TransformUsing(Transformers.AliasToBean<EmploymentDto>())
.List<EmploymentDto>();