HasManyToMany Fluent NHibernate Mapping Delete Error

北城以北 提交于 2019-12-10 22:37:40

问题


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:


you have to remove them manually

void Delete(Task task)
{
    foreach (var parent in task.Parents)
    {
        parent.Childs.Remove(task);
    }
    session.Delete(task);
}


来源:https://stackoverflow.com/questions/9474368/hasmanytomany-fluent-nhibernate-mapping-delete-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!