我的实体是这些:
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">的定义,并且找不到接受类型为"System.Data.Entity.ModelConfiguration.Configuration.Configuration.RequiredNavigationPropertyConfiguration"的第一个参数的扩展方法"WillCascadeOnDelete"(是否缺少 using 指令或程序集引用? D:\Work\C# Projects\Visual Studio 2010\Windows\WPF\New folder\Accounting Without EF Code First\Accounting - Copy\DAL.英 孚。CodeFirst\Entities\Context\AccountingContext.cs 22 22 DAL.英 孚。代码优先
我想删除客户级联的付款(只是在客户被删除的情况下(。 如何首先在 EF 代码中实现此目的?
我也想使用级联更新。请在这些问题上帮助我。谢谢。
说明
您需要在上下文中配置模型构建器。
样本
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);
}
}
在模型创建方法上,您需要进行如下更改
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;
}
}