配置级联删除

时间:2013-08-19 15:34:35

标签: c# .net entity-framework-5

我有8个对象引用了一个名为ExpenseType的通用实体。 8个对象之间有36个对ExpenseType的引用。我想配置级联删除,以便在删除引用对象时,ExpenseType记录也是如此。

我正在使用Code First Entity Framework 5并且已经为我的架构中的其他对象执行了此操作,但是这种通用性质让我感到难过。

非常感谢任何和所有帮助。

由于 约翰

public class HouseholdExpenses
    {
        [Key]
        public virtual int HouseholdExpensesId { get; set; }

        [Display(Name = "Childcare")]
        public virtual ExpenseType Childcare { get; set; }

        [Display(Name = "Elderly Care (Carer Nursing Home etc)")]
        public virtual ExpenseType ElderlyCare { get; set; }

        [Display(Name = "Food / Housekeeping / Personal Care")]
        public virtual ExpenseType FoodHousekeeping { get; set; }

        [Display(Name = "Clothing and Footwear")]
        public virtual ExpenseType ClothingFootwear { get; set; }

        [Display(Name = "House Repairs and Maintenance")]
        public virtual ExpenseType RepairsAndMaintenance { get; set; }
}

    public class MedicalExpenses
    {
        [Key]
        public virtual int MedicalExpensesId { get; set; }

        [Display(Name = "Medical Expenses and Prescription Charges")]
        public virtual ExpenseType MedicalExpensesAndPrescriptions { get; set; }

        [Display(Name = "Health Insurance (unless deducted from your salary at source)")]
        public virtual ExpenseType HealthInsurance { get; set; }
}

public class ExpenseType
{
    [Key]
    public virtual int ExpenseTypeId { get; set; }

    [Display(Name = "Amount")]
    public virtual decimal? Amount { get; set; }

    [Display(Name = "Arrears")]
    public virtual decimal? Arrears { get; set; }
}

1 个答案:

答案 0 :(得分:0)

覆盖OnModelCreating并尝试此操作。除非我忘了我认为它应该有用的东西。

mBuilder.Entity<ExpenseType>()
            .HasRequired(he => he.Childcare)
            .WithMany();

mBuilder.Entity<ExpenseType>()
            .HasRequired(ec => ec.ElderlyCare)
            .WithMany();
...