[英]Entity framework code first cascading deletes on 0..1 to many
I'm using this kind of model for a 0..1 to many relationship. 我正在将这种模型用于0..1到许多关系。 A Page must either have a valid book id or null. 页面必须具有有效的书籍ID或为null。
public class Book
{
[Key]
public Guid Id { get; set; }
public virtual List<Page> Pages { get; set; }
}
public class Page
{
[Key]
public Guid Id { get; set; }
public virtual Book Book { get; set; }
}
I want to add cascading deletes, so that if a book is deleted then all of its pages are also deleted, not set to null. 我想添加级联删除,以便如果删除一本书,那么它的所有页面也将被删除,而不是设置为null。
I can (only?) do this with the fluent api: 我可以(只有?)使用流利的api来做到这一点:
modelBuilder.Entity<Page>()
.HasOptional(a => a.Book)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
Using [Required]
is not suitable, because the field is not required. 不适合使用[Required]
,因为该字段不是必填字段。
However, this creates another column Book_Id1
, index and foreign key in the database, rather than adding cascading deletes on the existing FK, because it's defined twice. 但是,这将在数据库中创建另一列Book_Id1
,索引和外键,而不是在现有FK上添加级联删除,因为它被定义了两次。
If I comment out the Book.Pages
property, it works, but I lose the ability to call book.Pages and have to instead call dbcontext.Pages.Where(p => p.Book.Id == book.Id)
, which is not ideal because I don't want the calling code to have to know about the dbcontext object. 如果我注释掉Book.Pages
属性,它可以工作,但是我无法调用book.Pages,而必须调用dbcontext.Pages.Where(p => p.Book.Id == book.Id)
,这是不理想的,因为我不希望调用代码必须了解dbcontext对象。
Is there a way to have both the Book.Pages
property and cascading deletes? 有没有办法同时具有Book.Pages
属性和级联删除? Perhaps setting both to use the same FK name? 也许将两者都设置为使用相同的FK名称?
i think in codefirst you have to try this 我认为在代码第一,你必须尝试这个
dbcontext.Page.RemoveRange(book.Pages);
dbcontext.Book.Remove(book);
dbContext.SaveChanges();
here what you can do 在这里你可以做什么
public class Book
{
[Key]
public Guid Id { get; set; }
public virtual List<Page> Pages { get; set; }
}
public class Page
{
[Key]
public Guid Id { get; set; }
public Guid BookId { get; set;}
//[ForeignKey("BookId")] you can add the fluent here or during entity builder
public virtual Book Book { get; set; }
}
modelBuilder.Entity<Page>()
.HasOptional(a => a.Book)
.WithMany(a=>a.Pages)
.HasForeignKey(a=>a.BookId)
.WillCascadeOnDelete(true);
var pages= dbcontext.Pages.Where(p => p.BookId == book.Id); // this will work
this code should work normally for you 该代码应为您正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.