gpt4 book ai didi

c# - EF Code First 级联删除和更新?

转载 作者:太空狗 更新时间:2023-10-29 17:38:12 25 4
gpt4 key购买 nike

我的实体是这些:

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() 中得到这个错误:

Error 1 'System.Data.Entity.ModelConfiguration.Configuration.RequiredNavigationPropertyConfiguration' does not contain a definition for 'WillCascadeOnDelete' and no extension method 'WillCascadeOnDelete' accepting a first argument of type 'System.Data.Entity.ModelConfiguration.Configuration.RequiredNavigationPropertyConfiguration' could be found (are you missing a using directive or an assembly reference?) 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

我想删除客户级联的付款(Just if 客户被删除)。我如何首先在 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);
}
}

关于c# - EF Code First 级联删除和更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com