加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:15:26 所属栏目:百科 来源:网络整理
导读:我的实体是这些: public class Customer{ public Customer() { Invoices = new ListInvoice(); Payments = new ListPayment(); } public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public IListPa
我的实体是这些:
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:WorkC# ProjectsVisual Studio 2010WindowsWPFNew folderAccounting Without EF Code FirstAccounting – CopyDAL.EF.CodeFirstEntitiesContextAccountingContext.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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读