Nhibernate 不会从集合中删除子项

JBl*_*and 3 collections nhibernate parent-child

首先是映射,

<set name="Comments" table="cm_events_venue_comment" inverse="true"
        lazy="true" generic="true" cascade="all-delete-orphan"
        batch-size="10" order-by="dateCreated ASC">
    <cache usage="read-write" />
    <key column="venueId" />
    <one-to-many class="VenueComment" />
</set>
Run Code Online (Sandbox Code Playgroud)

一次通过考试,

[Test]
public void CanSaveAndDeleteComments()
{
    User u = TestDataHelper.CreateUser("Sir", "Talkalot");
    VenueComment comment;
    Venue v = GetVenueById();

    PerformInTransaction(() =>
    {
        userRepository.SaveOrUpdate(u);
        comment = new VenueComment()
        {
            Commenter = u,
            Text = "I like ifs and buts and i cannot lie..",
            DateCreated = DateTime.Now
        };
        v.AddComment(comment);
        comment = new VenueComment()
        {
            Commenter = u,
            Text = "And words ending in 'ly'",
            DateCreated = DateTime.Now
        };
        v.AddComment(comment);
        Assert.DoesNotThrow(()=>venueRepository.SaveOrUpdate(v));
    });

    // Test retrieval 
    Session.Evict(v);

    v = GetVenueById();
    v.Comments.Count.ShouldEqual(2);
    var c = v.Comments.FirstOrDefault<VenueComment>();
    c.Commenter.Id.ShouldEqual(u.Id);

    // and deletion
    PerformInTransaction(() =>
    {
        v.RemoveComment(c);
    });

    Session.Evict(v);
    v = GetVenueById();
    v.Comments.Count.ShouldEqual(1);

}
Run Code Online (Sandbox Code Playgroud)

我的问题出现在我的应用程序的控制器中,

[Authenticate, AcceptAjax]
public ActionResult DeleteComment(int id)
{
    return PerformInTransaction<ActionResult>(() =>
        {
            var comment = commonDao.GetObjectById<VenueComment>(id);
            if (comment == null)
                return JsonFailure("Comment not found");

            if (comment.Commenter.Id == CurrentUser.Id ||
                AuthUtil.IsAdministrator()) //
            {

               var venue = comment.Venue;
               venue.RemoveComment(comment);

                return JsonSuccess(id);
            }
            return JsonFailure("You can only delete comments you created.");
        });
}
Run Code Online (Sandbox Code Playgroud)

根据 Log4Net 的说法,没有发布删除。正如我所说,上面的测试通过了,所以映射应该是正确的。

有什么线索吗?

yfe*_*lum 5

如果您查看inverse有关集合类型属性映射的属性的文档,您会发现该设置inverse="false"指示 NHibernate 监视父对象(包含集合的对象)对集合的更改,并插入/删除子对象基于在父母的孩子集合上添加/删除。

但是,当您设置时inverse="true",您是在指示 NHibernate 监视子对象是否将引用属性更改回父对象。所以当你设置孩子的 parent-reference 属性时,NHibernate 就会去修改关联。

看起来您不想设置inverse="true"父母的孩子集合。

附录:

RemoveComment可以将父级与子级分离(如 set child.Parent = null)。但是,如果它不也是从撇清孩子Session,如果集合标志着inverse="true"这说明孩子拥有的关联,而不是集合拥有的关联,然后NHibernate的将不会发送下来deletedelete如果对象应该被删除,NHibernate 只会向下发送a) 如果集合拥有关联 ( inverse="false") 并且集合的级联设置为包括删除并且对象从集合中删除,或者 b) 如果对象是从Session.