1

I have created two tabled called Customer and destination . CustomerCode is a primary key in Customer and Foreign key is Destination .when i delete a customer the destination will be deleted.

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; }
}
kara
  • 3,205
  • 4
  • 20
  • 34
Daivshala
  • 11
  • 3
  • use this link: https://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations – hassan.ef May 08 '19 at 06:46

1 Answers1

0

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

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<Customer>()
        .HasOptional(d => d.Destination)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32