我有两张桌子,BookCategory & Books。一个类别可以有多本书。我正在使用实体框架。在删除特定 BookCategory 时,我想删除同一类别的所有书籍。
我不确定在哪里设置 OnDelete = Cascade 的规则。以下是我的代码。
如果需要更多信息,请告诉我。
1]我的数据库(bookCatalog.Context.cs)
namespace LearningEF
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class bookCatalogEntities : DbContext
{
public bookCatalogEntities()
: base("name=bookCatalogEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<BookCategory> BookCategories { get; set; }
public virtual DbSet<Book> Books { get; set; }
}
}
2]我的书课(Book.cs)
namespace LearningEF
{
using System;
using System.Collections.Generic;
public partial class Book
{
public Book()
{
}
public int Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public Nullable<int> Category { get; set; }
public virtual BookCategory BookCategory { get; set; }
}
}
3] 我的 BookCategories 类(BookCategory.cs)
namespace LearningEF
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class BookCategory
{
public BookCategory()
{
this.Books = new HashSet<Book>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}
4]图表xml(bookCatalog.edmx.diagram)
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram DiagramId="3da0fdfb8bce456da4d1833a61ed8d58" Name="Diagram1">
<EntityTypeShape EntityType="bookCatalogModel.Author" Width="1.5" PointX="0.75" PointY="1.25" IsExpanded="true" />
<EntityTypeShape EntityType="bookCatalogModel.BookCategory" Width="1.5" PointX="0.75" PointY="5.25" IsExpanded="true" />
<EntityTypeShape EntityType="bookCatalogModel.Book" Width="1.5" PointX="3" PointY="0.875" IsExpanded="true" />
<EntityTypeShape EntityType="bookCatalogModel.sysdiagram" Width="1.5" PointX="2.75" PointY="4.75" IsExpanded="true" />
<AssociationConnector Association="bookCatalogModel.FK_Books_BookCategories" ManuallyRouted="false" />
<AssociationConnector Association="bookCatalogModel.BookAuthors" ManuallyRouted="false" />
</Diagram>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
但是在删除 BookCategory 时出现以下错误。
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code
Additional information: An error occurred while updating the entries. See the inner exception for details.
这是我删除类别的代码
BookCategory deleteBookCat = dbCatlog.BookCategories.SingleOrDefault(p => p.Id.Equals(1));
dbCatlog.BookCategories.Remove(deleteBookCat);
dbCatlog.SaveChanges();