简体   繁体   English

NHibernate'Where'子句导致级联删除问题

[英]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" />
    </bag>
</class>

I want to apply a Where clause against the 'Comments' bag to only retrieve Comments with the 'Approved' property = true. 我想对“注释”包应用Where子句,以仅检索“ Approved”属性为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! 但是,当我将其放置在适当的位置时,我遇到了一个问题场景,即删除的Photo对象没有被层叠,然后级联删除了未经批准的注释(并留下了孤立的注释记录),因为它不符合where子句的条件! 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. 本质上,我希望将EXCEPT附加到where子句以进行级联删除,在这种情况下,我总是希望在删除照片时删除与照片相关的所有注释。

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. 由于NHibernate无法猜测您“希望将EXCEPT遵循的where子句进行级联删除” ,因此您需要使用过滤器来获取集合项。

An alternative is using a LINQ-to-objects projection: 一种替代方法是使用LINQ到对象的投影:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM