EF Code first cascade delete on foreign key one-to-many

c# entity-framework sql-server-ce


We are working in Entity framework Code first

We have a class video

class Video{
   List<ImageInfo> Images{
      get; set;

our image infoclass contains a path to the image and some other info

class ImageInfo{
    String path;

we would like to have EF remove the imageinfos when removing the video

so we changed the modelbuilder like follows:

    .HasMany(v => v.Images)

we don't want to add a link back to video in our imageinfo class.

is it possible to get cascade delete functionality without a 2 way foreign key?


the video_id of the imageInfo doesn't get filled in in the database when saving a video.


how can we fix this?

I don't know if its related, but when we add a new video with images at the same time, we get this error:

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
2/15/2013 8:46:30 PM

Popular Answer

The WithRequired introduces the 2 way relationship. So you should do the following.

    .HasMany(v => v.Imgages)

... and assuming you want the relationship the other way around ...

public class Video { }
public class ImageInfo {
    public virtual Video { get; set; }

    .HasRequired(v => v.Video)

PS: I think the List<ImageInfo> should be virtual, so here is how I'd define it ...

public class Video {
    public Video() { this.Images = new List<ImageInfo>(); }
    public virtual ICollection<ImageInfo> Images { get; set; }
2/15/2013 4:36:31 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow