9

我的实体是这些:

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 without EF Code First\Accounting - Copy\DAL.EF.CodeFirst \Entities\Context\AccountingContext.cs 22 22 DAL.EF.CodeFirst

我想删除客户级联的付款(就像客户被删除一样)。我怎样才能首先在 EF 代码中实现这一点?

我也想使用级联更新。请在这些问题上帮助我。谢谢。

4

2 回答 2

17

描述

您需要在您的上下文中配置模型构建器。

样本

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);
    }
}
于 2012-05-09T20:11:19.167 回答
0

在模型创建方法上,您需要进行如下更改

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
            //Disabling Delete Cascade
            foreach (var foreignKey in modelBuilder.Model.GetEntityTypes().SelectMany(model=>model.GetForeignKeys()))
            {
                //Disabling Delete Cascade on Each Entities
                foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
            }
}
于 2022-01-02T12:28:32.123 回答