0

简单地说,我有这 3 个类

class Bag { int Id; }

class Candy { int Id; }

class CandyBag
{
    int Id;
    Candy candy;
    Bag bag;
}

我需要列出所有包含某种糖果的包,我认为它是这样的:

session.QueryOver<Bag>(() => bagAlias)
    .JoinQueryOver<CandyBag>()
        .Where(candyBag => candgyBag.Bag.Id == bagAlias.Id)
        .And(candyBag => candgBag.Candy.Id == userSelectedCandy.Id)
    .List();  

问题是,我不能在 Bag 类中拥有 CandyBag 或 Candy 的属性,因为我有更多的包可以容纳的物品(如 Cloth/ClothBag Food/FoodBag)。我这么说是因为我做不到

session.QueryOver<Bag>(() => bagAlias)
    .JoinQueryOver<CandyBag>(bag => bag.CandyBag, () => candyBagAlias)
        .Where(candyBag => candyBag.Bag.Id == bagAlias.Id)
    .List();  

提前致谢。

4

1 回答 1

0

根据您的示例,我创建了此类:

public class Bag { 
    public int Id {get; set;} 
}
public class Candy {
    public int Id { get; set; } 
}
public class CandyBag
{
    public int Id { get; set; }
    public Candy Candy { get; set; }
    public Bag Bag { get; set; } 
}

和这个 NHibernate 映射

 <class name="Bag" table="Bag" lazy="false" >
        <id name="Id">
            <generator class="identity" />
        </id>
        <!--<property name="CreationDate" />-->
    </class>
    <class name="Candy" table="Candy" lazy="false" >
        <id name="Id">
            <generator class="identity" />
        </id>
        <!--<property name="CreationDate" />-->
    </class>
    <class name="CandyBag" table="CandyBag" lazy="false" >
        <id name="Id">
            <generator class="identity" />
        </id>
        <many-to-one name="Candy" column="CandyId" lazy="false" />
        <many-to-one name="Bag" column="BagId" lazy="false" />
    </class>

获得某糖果包的收集:

IList<Bag> bags = null;
using (var session = OpenSession())
{
    CandyBag candyBagAlias = null;
    bags = session.QueryOver<CandyBag>(() => candyBagAlias)     
        .Where(() => candyBagAlias.Candy.Id == userSelectedCandyId )
        .List()
        .Select(cb => cb.Bag).ToList();

    // or with LINQ
    bags = (
        from bag in session.Query<Bag>()
        join candyBag in session.Query<CandyBag>() on bag equals candyBag.Bag
        where candyBag.Candy.Id == userSelectedCandyId 
        select bag 
    ).ToList();
}
return bags;

我更喜欢 LINQ 方式,因为它非常容易理解。

于 2014-02-22T20:25:16.443 回答