HasManyToMany Fluent NHibernate Mapping Delete Err

2019-07-06 21:33发布

I have been working on a many to many mapping on an entity i have called Task. A task can have many children and many parents. There is a join table in between which just has the two FK columns "ParentTaskId" and "ChildTaskId". Here is what I have come up with so far.

        // Many-to-Many Parents
        HasManyToMany<Task>(x => x.Parents)
            .Table("TaskDependency")
            .ParentKeyColumn("ParentTaskId")
            .ChildKeyColumn("ChildTaskId")
            .Inverse()
            .Not.LazyLoad()
            .Cascade.SaveUpdate();

        // Many-to-Many Children
        HasManyToMany<Task>(x => x.Children)
            .Table("TaskDependency")
            .ParentKeyColumn("ChildTaskId")
            .ChildKeyColumn("ParentTaskId")
            .Not.LazyLoad()
            .Cascade.SaveUpdate();

And here is some example code to help me illustrate my question. The code below works:

        _taskRepository.Save(_taskVendor);
        _taskRepository.Save(_taskClientVendor);
        _taskRepository.Save(_taskClient);

        _taskVendor.Children.Add(_taskClientVendor);
        _taskClientVendor.Children.Add(_taskClient);
        _taskRepository.Save(_taskVendor);
        _taskRepository.Save(_taskClientVendor);

        _taskRepository.Delete(_taskVendor);
        _taskRepository.Delete(_taskClientVendor);
        _taskRepository.Delete(_taskClient);

But if I change the order of the delete statements to be:

        _taskRepository.Delete(_taskVendor);
        _taskRepository.Delete(_taskClient);
        _taskRepository.Delete(_taskClientVendor);

I get a fk constraint violation on my many to many join table. I think this has to do with the way I have inverse set up on my mapping. It effects the order in which queries are executed to avoid this exact fk constraint issue. Is there any way to map this so that I could delete entities on either side, child or parent, without having this exception? I tried inverse on both sides of my mapping but that just resulted in my many to many relationship not getting saved. >_<

Any help would be much appreciated.

1条回答
Rolldiameter
2楼-- · 2019-07-06 22:03

you have to remove them manually

void Delete(Task task)
{
    foreach (var parent in task.Parents)
    {
        parent.Childs.Remove(task);
    }
    session.Delete(task);
}
查看更多
登录 后发表回答