简体   繁体   English

如何在实体框架中对外键应用级联删除

[英]how to apply cascade-delete on foreign key in entity framework

I have created two tabled called Customer and destination . 我创建了两个表Customer和destination。 CustomerCode is a primary key in Customer and Foreign key is Destination .when i delete a customer the destination will be deleted. 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; }
}

Your probable model will be 您可能的模型将是

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

You need to use the fluent API and add following code in DBContext 您需要使用流利的API并在DBContext中添加以下代码

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<Customer>()
        .HasOptional(d => d.Destination)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM