9

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:

modelBuilder
    .Entity<Video>()
    .HasMany(v => v.Images)
    .WithRequired()
    .WillCascadeOnDelete(true);

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?

EDIT

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

http://pbrd.co/14X82vb

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.
Alexander Cosman
  • 1,117
  • 11
  • 20

1 Answers1

18

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

modelBuilder
    .Entity<Video>()
    .HasMany(v => v.Imgages)
    .WithOptional()
    .WillCascadeOnDelete(true);

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

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

modelBuilder
    .Entity<ImageInfo>()
    .HasRequired(v => v.Video)
    .WithMany()
    .WillCascadeOnDelete(true);

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; }
}
AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
  • Works like a charm. We also had a second problem. We assigned a new list to the Images property, causing the database synchronization to fail. So we learned to never assign a new list to a property. (similar with observableCollection and databinding) – Alexander Cosman Feb 15 '13 at 18:55
  • Acceptance of the answer would be greatly appreciated then :-). Plus it also helps your own reputation leading to more/better answers. – AxelEckenberger Feb 15 '13 at 19:19
  • we still have the problem of cascading the images on deleting a video: see original question (edited part) – Alexander Cosman Feb 15 '13 at 20:47