【问题标题】:Join on tables using Fluent NHibernate使用 Fluent NHibernate 加入表
【发布时间】:2015-01-19 15:02:07
【问题描述】:

我想使用 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来做的,那么变量shops我得到如下数组:

1               Bargin Basin    Daisy       
1               Bargin Basin    Daisy
1               Bargin Basin    Daisy

我使用 FN 版本 2.0.1.0,NHibernate 4.0。谢谢。

【问题讨论】:

    标签: c# nhibernate left-join fluent


    【解决方案1】:

    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>();
    

    【讨论】:

    • 正确版本:var就业 = session.QueryOver() .Where(shop => shop.Id == 1) .JoinAlias(s => s.Staff, () => employee ) .SelectList(l => l.Select(s => s.Id).WithAlias(() => dto.StoreId) .Select(s => s.Name).WithAlias(() => dto.StoreName) .Select(() => employee.FirstName).WithAlias(() => dto.FirstName)) .TransformUsing(Transformers.AliasToBean()) .List();
    • 和答案中的那个有什么区别?您能突出显示以便我修复它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    相关资源
    最近更新 更多