c# - 如何在实体框架中对外键应用级联删除
问题描述
我创建了两个名为 Customer 和 destination 的表格。CustomerCode 是 Customer 中的主键,外键是 Destination 。当我删除客户时,目的地将被删除。
public class tblCustomerDetails
{
[Key]
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
}
public class tblDestinationDetails
{
[Key]
public string DestinationCode { get; set; }
[ForeignKey("tblCustomerDetails")]
public string CustomerCode { get; set; }
public tblCustomerDetails tblCustomerDetails { get; set; }
public string DestinationName { get; set; }
}
public class tblOrderDetails
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int SrNo { get; set; }
public int OrderNo { get; set; }
[ForeignKey("tblCustomerDetails")]
public string CustomerCode { get; set; }
public tblCustomerDetails tblCustomerDetails { get; set; }
[ForeignKey("tblDestinationDetails")]
public string DestinationCode { get; set; }
public tblDestinationDetails tblDestinationDetails { get; set; }
}
解决方案
您可能的模型将是
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomerCode { get; set; }
public virtual Destination destination { get; set; }//relationship with Destination
}
public class Destination
{
public virtual Customer customer { get; set; }//relationship with Customer
[Key, ForeignKey("User")]
public int CustomerCode { get; set; }
}
您需要使用 fluent API 并在 DBContext 中添加以下代码
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasOptional(d => d.Destination)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
推荐阅读
- android - 如何从活动中的片段中从 Radio Group 中获取选定的 Radio Button?
- angular - 如何使用 Angular DI 注入已声明的命名空间?
- javascript - JS:将事件侦听器添加到节点列表
- c++ - 打包修剪过的 C 结构体
- mysql - 更新表的远程副本中的地址
- java - 如何使用 Selenium Webdriver 验证浏览器通知
- javascript - 点击事件
不适用于 IONIC 3 应用程序的 iOS - android - Android:更改清单中的 BroadcastReceiver 属性可以阻止它在用户更新应用程序时接收广播吗?
- html - 是否期望输入密码自动提交?
- mysql - SQL:按日期范围查找数据