c# – EF代码首先级联删除和更新?

前端之家收集整理的这篇文章主要介绍了c# – EF代码首先级联删除和更新?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的实体是这些:
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

我想删除客户级联付款(只要客户被删除).我如何才能在EF代码中实现这一点?

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

解决方法

描述

您需要在您的上下文中配置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);
    }
}
原文链接:/csharp/92270.html

猜你在找的C#相关文章