nhibernate "cascade="all-delete-orphan" error

leora picture leora · Apr 27, 2011 · Viewed 7.3k times · Source

i have 3 tables in my database:

  1. Projects (id, name)
  2. Tags (id, name)
  3. ProjectsTagss (id, projectId, tagid)

As you can see the ProjectsTags table is a bridge table

here is my fluent nhibernate mapping

ProjectMap.cs:

 Map(x => x.Name).Not.Nullable();
 HasMany(x => x.ProjectsTags).AsBag().Inverse()
    .Cascade.AllDeleteOrphan().Fetch.Select().BatchSize(80);

ProjectsTagsMap.cs:

 References(x => x.Project).Not.Nullable();
 References(x => x.Tag).Not.Nullable();

TagMap.cs:

  Map(x => x.Name).Not.Nullable();

As you can see, i historically didn't have the Tag table linked to anything else. I now need to generate a report to show Tag and how often that tag is used so i need to join from Tag to ProjectsTag. i tried adding this line into the tagsmap:

 HasMany(x => x.ProjectsTags).AsBag().Inverse()
    .Cascade.AllDeleteOrphan().Fetch.Select().BatchSize(80);

but when i go to update the name on a tag object and commit, i get this error:

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance

can anyone see anything wrong with what i added that would be causing this nhibernate exception when i simply update the Tag table. Again my goal is to be able to do something like:

 Tag.ProjectTags.Count();

Here is some additional code as requested:

my Tag Class:

 public class Tag
{
    public virtual IList<ProjectTag> ProjectTags { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
}

Answer

Serhat Ozgel picture Serhat Ozgel · May 4, 2011

Somewhere in your code, you should have dereferenced the original collection on your Project domain. I suspect that your code goes like this:

var project = Session.Get<Project>();
project.ProjectsTags = new List<ProjectsTags> { someProjectsTagsInstance };
Session.Save(project);

If this is the case, you should do this instead:

var project = Session.Get<Project>();
project.ProjectsTags.Clear();
project.ProjectsTags.Add(someProjectsTagsInstance);
Session.Save(project);