[英]EF Code first cascade delete on foreign key one-to-many
We are working in Entity framework Code first 我们首先在Entity框架代码中工作
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 我们的图像infoclass包含图像的路径和一些其他信息
class ImageInfo{
String path;
...
}
we would like to have EF remove the imageinfos when removing the video 我们希望在删除视频时让EF删除imageinfos
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. 我们不想在imageinfo类中添加回到视频的链接。
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. 保存视频时,imageInfo的video_id不会填入数据库。
http://pbrd.co/14X82vb 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.
The WithRequired
introduces the 2 way relationship. WithRequired
引入了双向关系。 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 ... PS:我认为
List<ImageInfo>
应该是virtual
,所以这里是我如何定义它...
public class Video {
public Video() { this.Images = new List<ImageInfo>(); }
public virtual ICollection<ImageInfo> Images { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.