I have a simple table-per-subclass inheritance with the following NHibernate mapping
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default- cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="BillingDetail table="BillingDetails">
<id name="Id" type="System.Int32">
<column name="Id" />
<generator class="identity" />
</id>
<property name="DateAdded" type="System.DateTime">
<column name="DateAdded" />
</property>
<many-to-one class="Account name="Account">
<column name="Account_id" />
</many-to-one>
<joined-subclass name="BankAccount table="BillingDetails_BankAccount">
<key>
<column name="Id"/>
</key>
<property name="AccountNumber" type="System.Int64">
<column name="AccountNumber" />
</property>
<property name="SortCode" type="System.Int32">
<column name="SortCode" />
</property>
</joined-subclass>
<joined-subclass name="CreditCard table="BillingDetails_CreditCard">
<key>
<column name="Id" />
</key>
<property name="CardNumber" type="System.Int64">
<column name="CardNumber" />
</property>
<property name="CardType" type="System.String">
<column name="CardType" />
</property>
<property name="ExpiryDate" type="System.DateTime">
<column name="ExpiryDate" />
</property>
</joined-subclass>
</class>
</hibernate-mapping>
So bot开发者_开发技巧h Credit Card and Bank Account inherit from "Billing Detail". Within my domain layer I have the following statement:
var billingDetail = (from a in unitOfWork.Context.BillingDetail.OfType<CreditCard>()
select a).FirstOrDefault();
The "unitOfWork.Context" property above just gives me access to the ISession unit of work. When I run the application I get the following error:
BillingDetail = 'unitOfWork.Context.BillingDetail' threw an exception of type 'NHibernate.PropertyAccessException' Message = "Invalid Cast (check your mapping for property type mismatches); setter of BankAccount"
If I put a breakpoint at the "var billingDetail..." statement and run the program to inspect this error I can see the above message. However, if I then click play to continue program execution, instead of bombing out with the above message, the program runs successfully and enters all the data into the database. Without inspecting the breakpount, the program crashes (as I'd expect if there's actually a problem with the mappings).
What appears to be happening is that every time it sees a "BankAccount" entity is gives the exception, but all CreditCard entities are fine. Is there something wrong with the "OfType" that it doesn't filter out the BankAccount objects?
Answer here was nothing interesting. I should have paid more attention to the full error which said:
Invalid Cast (check your mapping for property type mismatches)
When I did what the error told me I saw a column which was mapped as an Int32 but should have been Int64. Not very clever of me.
精彩评论