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.
source share