как применить каскад-удаление к внешнему ключу в рамках сущности - PullRequest
1 голос
/ 08 мая 2019

Я создал две таблицы под названием Клиент и пункт назначения.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; }
}

1 Ответ

0 голосов
/ 08 мая 2019

Ваша вероятная модель будет

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

Вам необходимо использовать свободный API и добавить следующий код в DBContext

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