Cascading with Castle ActiveRecord HasAndBelongsToMany's
I am having a lot of problems with cascading delete via HasAndBelongsToMany relationship using Castle ActiveRecord / NHibernate.
I have photos that have and belong to many tags. Attached to these is a table called PhotoHasTag, which only contains the photosId and tagId file. When I remove a photo, I would like all associated PhotoHasTags to be removed, as well as any orphaned tags that need to be removed.
Right now I have my photo class setup something like this:
[ActiveRecord(Table="Photo")]
public class Photo
{
[PrimaryKey(Column = "photoId", Generator = Castle.ActiveRecord.PrimaryKeyType.Identity)]
public virtual int Id { get; set; }
[HasAndBelongsToMany(Table="PhotoHasTag",ColumnKey="photoId",ColumnRef="tagId",Lazy=true,Cascade=ManyRelationCascadeEnum.AllDeleteOrphan)]
public virtual IList<Tag> Tags { get; set; }
}
And my Tag class is configured roughly the same:
[ActiveRecord(Table="Tag")]
public class Photo
{
[PrimaryKey(Column = "tagId", Generator = Castle.ActiveRecord.PrimaryKeyType.Identity)]
public virtual int Id { get; set; }
[HasAndBelongsToMany(Table = "PhotoHasTag", ColumnKey = "tagId", ColumnRef = "photoId", Lazy = true)]
public IList<Photo> Photos { get; set; }
}
When I try to delete a photo, I get an error from SQL Server:
The DELETE statement conflicted with the REFERENCE constraint "PhotoHasTag_FK1".
I can work around this in SQL Server by setting the Delete Rule to Key to Cascade, but then only the PhotoHasTag is removed. If there are any orphaned tags, they will still linger in the database.
I'm thinking of writing a trigger to take care of the tags on the left, but I'd be much happier if there was a way to tweak my ActiveRecord mappings to remove the cascades.
Thanks in advance, I am stuck on this forever so I appreciate any help!
You can specify cascading behavior in attributes like this:
[HasAndBelongsToMany(Table = "PhotoHasTag", Cascade=ManyRelationCascadeEnum.AllDeleteOrphan, ColumnKey = "tagId", ColumnRef = "photoId", Lazy = true)]
public IList<Photo> Photos { get; set; }
The API documentation is probably more helpful.
source to share