C# 实体框架中外键级联删除的应用
我创建了两个名为Customer和destination的表格。CustomerCode是Customer中的主键,外键是Destination。当我删除客户时,Destination将被删除C# 实体框架中外键级联删除的应用,c#,entity-framework-6,cascading-deletes,C#,Entity Framework 6,Cascading Deletes,我创建了两个名为Customer和destination的表格。CustomerCode是Customer中的主键,外键是Destination。当我删除客户时,Destination将被删除 public class tblCustomerDetails { [Key] public string CustomerCode { get; set; } public string CustomerName { get; set; } } public class tbl
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; }
}
您需要使用fluentapi并在DBContext中添加以下代码
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasOptional(d => d.Destination)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.has可选(d=>d.Destination)
.WithOptionalDependent()
.WillCascadeOnDelete(真);
}
您可能的型号为
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; }
}
您需要使用fluentapi并在DBContext中添加以下代码
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasOptional(d => d.Destination)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.has可选(d=>d.Destination)
.WithOptionalDependent()
.WillCascadeOnDelete(真);
}
使用此链接:使用此链接: