开发者

NHibernate 'Where' Clause causing problems on cascading deletes

I have the following mapping file for 'Photo' objects (edited for brevity):

<hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" lazy="false" order-by="DateTimePosted desc" cascade="all-delete-orphan" inverse="true">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    开发者_如何学JAVA</bag>
</class>

I want to apply a Where clause against the 'Comments' bag to only retrieve Comments with the 'Approved' property = true. However, when I had this in place I came up against a problem scenario where deleted Photo objects were not then cascading deleted unapproved comments (and were leaving orphaned comment records) as it didn't meet the condition of the where clause! In essence, I wanted the where clause to be adhered to EXCEPT for cascading deletes, in which case, I ALWAYS wanted any comments associated with a photo to be deleted, when a Photo was deleted.

Here is an edited copy of my Comments mapping file:

<hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    <property name="DateTimePosted" not-null="true" />
    ...
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo">
        <column name="PhotoId" />
    </many-to-one>
</class>

How can I get around this?


Since NHibernate can't guess that you "wanted the where clause to be adhered to EXCEPT for cascading deletes", you need to use filters to get the collection items instead.

An alternative is using a LINQ-to-objects projection:

public virtual IEnumerable<Comment> ApprovedComments
{
    get { return Comments.Where(c => c.Approved); }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜