NHibernate, "On Delete Cascade", a cascade that deletes rows in related tables?

I am using NHibernate (with Fluent-NHibernate mapping) in the project for the first time in the last few weeks, everything went well until today when I ran into a problem (most likely with my own error).

I made a small sample to illustrate what I'm trying to achieve:

public class Image { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual string Path { get; set; } } public class FeaturedImage { public virtual int Id { get; set; } public virtual Image Image { get; set; } public virtual string Description { get; set; } public virtual DateTime Date { get; set; } } public class ImageMap : ClassMap<Image> { public ImageMap() { Id(x => x.Id).GeneratedBy.Identity().UnsavedValue(0); Map(x => x.Name); Map(x => x.Path); } } public class FeaturedImageMap : ClassMap<FeaturedImage> { public FeaturedImageMap() { Id(x => x.Id).GeneratedBy.Identity().UnsavedValue(0); Map(x => x.Description); Map(x => x.Date); References(x => x.Image).Not.Nullable().Cascade.Delete(); } } 

In the above example, there are several images, every day one image is selected as a "perfect" image, the same image can be displayed several times. The behavior I would like is when I delete an image, any FeaturedImage records that reference this image identifier are automatically deleted. However, at the moment, if I try to delete the image that was shown, it causes an error:

The DELETE statement was contrary to the REFERENCE clause "FKF42D8269692640D". Conflict table "dbo.FeaturedImage", column "Image_id".

If you manually add "ENABLE DELETE CASCADE" to the foreign key constraint of the image, it works:

 alter table [FeaturedImage] add constraint FKF42D8269692640D foreign key ( Image_id ) references [Image] ON DELETE CASCADE 

... but I'm not sure if this is the recommended way to do this? If anyone could advise a better way to achieve this, we will be very grateful! Thanks in advance.

+6
source share
1 answer

The added .Cascade.Delete() does not match the relationship side, and this will actually result in the image being deleted when FeaturedImage is deleted.

What you want to do can be done by creating a FeaturedImage collection in the image, draw it as a back bag with cascading deletion in the key.

I do not use Fluent, but in XML you set on-delete="cascade" in the <key> collection element; find something like that.

+5
source

Source: https://habr.com/ru/post/893466/


All Articles