views:

42

answers:

1

Hi, I'm trying to delete an entity (ForumTopic) and have that delete the Posts (ForumPost) within it. Here are my entities:

public class ForumTopic
{
    public virtual int TopicID { get; set; }
    public virtual IList<ForumPost> Posts { get; private set; }

    ...

    public ForumTopic()
    {
        Posts = new List<ForumPost>();
    }
}

public class ForumPost
{
    public virtual int PostID { get; set; }
    public virtual ForumTopic Topic { get; set; }

    ...
}

With the following mappings:

public ForumTopicMap()
{
    Table("ForumTopics");
    Id(x => x.TopicID);
    HasMany(x => x.Posts)
        .Cascade.All();

    ...
}

public ForumPostMap()
{
    Table("ForumPosts");
    Id(x => x.PostID);
    References(x => x.Topic, "TopicID");

    ...
}

However when i delete my topic i receive the following error:

[ForumTopic.Posts#14][SQL: UPDATE ForumPosts SET TopicID = null WHERE TopicID = @p0]

This seems strange as I thought by saying Cascade.All() (I event tried Cascade.Delete()) on my HasMany mapping it would delete all the posts for this topic. I'd appreciate it if someone could show me what i'm doing wrong. Thanks

A: 

Try adding Inverse() to the HasMany mapping.

Diego Mijelshon
Cheers, worked a treat. It looks like i do need to understand this Inverse thing after all.
nfplee
It's not that hard. Every bidirectional relationship must have an "inverse" side, which is the side NOT in charge of maintaining it.
Diego Mijelshon
Cheers, i'm slowly understanding it. I also have a Subscriptions property on my Topic entity which contains a list of users who are subscribed to the topic. I have the same problem when deleting. I don't believe this is bi-directional since i don't have a TopicsSubscribed property against my user so inverse shouldn't be required to my understanding.However the same problem remains when deleting topics. I thought the cascade.all would take care of deleting the subscriptions but i guessed wrong again.
nfplee
Usually, the best pattern for cascading deletes is to have a bidirectional relationship with the DB doing the actual cascade. That way, a single SQL statement takes care of everything.
Diego Mijelshon