EF Code First级联删除和更新?

时间:2012-05-09 20:03:08

标签: c# entity-framework ef-code-first entity-framework-4.3

我的实体是:

public class Customer
{
    public Customer()
    {
        Invoices = new List<Invoice>();
        Payments = new List<Payment>();
    }

    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IList<Payment> Payments { get; set; }
}

public class Payment
{
    public int ID { get; set; }
    public int CustomerID { get; set; }
    public decimal CreditPrice { get; set; }
    public decimal DebitPrice { get; set; }
    public DateTime PaymentDate { get; set; }

    [ForeignKey("CustomerID")]
    public Customer Customer { get; set; }
}

这是我的背景:

public class AccountingContext : DbContext, IDisposable
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Payment> Payments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Payment>()
                .HasRequired(s => s.Customer)
                .WillCascadeOnDelete();

        base.OnModelCreating(modelBuilder);
    }
}

我在 WillCascadeOnDelete()中收到此错误:

  

错误1'System.Data.Entity.ModelConfiguration.Configuration.RequiredNavigationPropertyConfiguration'不包含'WillCascadeOnDelete'的定义,也没有扩展方法'WillCascadeOnDelete'接受类型'System.Data.Entity.ModelConfiguration.Configuration的第一个参数可以找到.RequiredNavigationPropertyConfiguration'(你是否缺少using指令或程序集引用?)D:\ Work \ C#Projects \ Visual Studio 2010 \ Windows \ WPF \ New folder \ Accounting没有EF Code First \ Accounting - Copy \ DAL。 EF.CodeFirst \ Entities \ Context \ AccountingContext.cs 22 22 DAL.EF.CodeFirst

我想删除客户级联的付款(只是客户被删除)。我怎样才能在EF代码中实现这一目标?

我也想使用级联更新。 请帮助我解决这些问题。 感谢名单。

1 个答案:

答案 0 :(得分:17)

描述

您需要在上下文中配置modelBuilder。

示例

public class AccountingContext : DbContext, IDisposable
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Payment> Payments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Payment>()
                .HasRequired(s => s.Customer)
                .WithMany()
                .WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
    }
}