EF代码首先级联删除外键一对多 [英] EF Code first cascade delete on foreign key one-to-many

查看:103
本文介绍了EF代码首先级联删除外键一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在实体框架代码中工作

We are working in Entity framework Code first

我们有一个类视频

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

我们的图像infoclass包含图像的路径和一些其他信息

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

class ImageInfo{
    String path;
    ...
}

我们想要EF删除imageinfos删除视频

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);

我们不想在imageinfo类中添加回到视频的链接。

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

是否可以在没有2路外键的情况下获得级联删除功能?

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

编辑

保存视频时,imageInfo的video_id不会在数据库中填写。

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.


推荐答案

WithRequired 介绍了2路关系。所以你应该执行以下操作。

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:我认为列表< ImageInfo> 应该是 virtual ,所以这里是我如何定义它...

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; }
}

这篇关于EF代码首先级联删除外键一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆