Whilst I realise that a Set or Bag is probably the correct way to do this, I'm new to NHibernate and I'm trying to understand why the following is happening.
I have two classes:
public class Customer
{
public virtual int Id { get; protected set; }
public virtual string CustomerName { get; set; }
// Customer has many domains
public virtual IList<Domain> Domains { get; set; }
}
public class Domain
{
public virtual int Id { get; protected set; }
public virtual int CustomerID { get; set; }
public virtual string DomainName { get; set; }
}
My mapping files look like:
<!-- Domain -> tblDomains -->
<class name="Domain" table="tblDomains">
<id name="Id">
<column name="DomainID" sql-type="int" not-null="true"/>
<generator class="identity"/>
</id>
<property name="CustomerID"/>
<property name="DomainName"/>
</class>
<!-- Customer -> tblCustomer -->
<class name="Customer" table="tblCustomer">
<id name="Id">
<column name="CustomerID" sql-type="int" not-null="true"/>
<generator class开发者_如何学编程="identity"/>
</id>
<property name="CustomerName" column="Customer"/>
<list name="Domains">
<key column="CustomerID"/>
<index column="DomainID"/>
<one-to-many class="Domain" />
</list>
</class>
When I retrieve a Customer
object the Domains
property contains a list of 665383 null Domain
objects. The 665384'th item in the list contains a valid populated object.
There are only 63 Domain
's that belong to this customer so I'm guessing this is some kind of cartesian product result. I've peeked at the SQL in NHProfiler but all I see is a query that looks fairly innocent when I iterate over the first item in the Domains
list:
SELECT domains0_.CustomerID as CustomerID1_,
domains0_.DomainID as DomainID1_,
domains0_.DomainID as DomainID2_0_,
domains0_.CustomerID as CustomerID2_0_,
domains0_.DomainName as DomainName2_0_
FROM tblDomains domains0_
WHERE domains0_.CustomerID = 5667 /* @p0 */
If I use a <bag>
this all works just fine. Can anyone explain what's going on under the bonnet?
With a list mapping, the index applies to the set of objects in the list. That is, if a Customer has a set of 63 Domains then normally the list would contain values from 0 to 62 to indicate the index of the Domain object in that Customer's set of Domains.
You have set the index to DomainId, the primary key of the table, which is wreaking havoc. I would guess that the Domain table has 665384 rows total (or fewer if DomainId doesn't start with 1 and has gaps), but I would think that 63 would be valid instead of one. Did you check them all? :-)
精彩评论