繁体   English   中英

实体框架-代码优先/ Fluent API-过滤的导航属性

[英]Entity Framework - Code First / Fluent API - Filtered navigation properties

我正在尝试使用代码优先方法和流畅的API定义以下三个类的关系,但是我已经走到了尽头。

给定以下三个类:

public class Contract {
  public Contract {
    this.PaymentRequests = new HashSet<PaymentRequest>();
    this.Bills = new HashSet<Bill>();
  }

  public long Id { get; set; }
  public virtual ICollection<PaymentRequest> PaymentRequests { get; set; }
  public virtual ICollection<Bill> Bills { get; set; }
}

public class Bill {
  public Bill {
    this.PaymentRequests = new HashSet<PaymentRequest>();
  }

  public long Id { get; set; }
  public virtual Contract Contract { get; set; }
  public virtual ICollection<PaymentRequest> PaymentRequests { get; set }
}

public class PaymentRequest {
  public long Id { get; set; }
  public virtual Contract Contract { get; set; }
  public virtual Bill Bill { get; set; }
}

我想通过以下方式定义关系:合同维护一个尚未设置帐单的PaymentRequests清单,以及一个包含将Bills设置为当前帐单的PaymentRequests清单的帐单清单。

因此,我尝试相应地设置映射:

public class ContractMap : EntityTypeConfiguration<Contract> {
  public ContractMap() {
    this.HasKey(x => x.Id);

    this.HasMany(x => x.PaymentRequests)
        .WithRequired(pr => pr.Contract);
    this.HasMany(x => x.Bills)
        .WithRequired(b => b.Contract);
  }
}

public class BillMap : EntityTypeConfiguration<Bill> {
  public BillMap() {
    this.HasKey(x => x.Id);

    this.HasRequired(x => x.Contract);
    this.HasMany(x => x.PaymentRequests)
        .WithRequired(x => x.Bill);
  }
}

public class PaymentRequestMap : EntityTypeConfiguration<PaymentRequest> {
  public PaymentRequestMap() {
    this.HasKey(x => x.Id);

    this.HasRequired(x => x.Contract);
    this.HasOptional(x => x.Bill);
  }
}

但这并不能真正起作用。 是否有可能定义这种关系,还是我需要创建另一个成员,例如,称为OpenPaymentRequests,并告诉EF忽略它,然后将其填充到(例如)存储库中,并对帐单中的PaymentRequests执行相同的操作? 我无法在网上找到类似内容,无法获得解决上述问题的最佳实践方法的有用信息。 任何输入都非常欢迎和赞赏!

您正在通过自己的ContractMapBillMap类将PaymentRequests配置为同时要求BillContract 出于您的目的, PaymentRequest只需要一个Contract - Bill应该是可选的(就像您在PaymentRequestMap类中选择的PaymentRequestMap ,由于前两个配置类,实际上并不需要)

public class ContractMap : EntityTypeConfiguration<Contract> {
  public ContractMap() {
    this.HasKey(x => x.Id);

    this.HasMany(x => x.PaymentRequests)
        .WithRequired(pr => pr.Contract);
    this.HasMany(x => x.Bills)
        .WithRequired(b => b.Contract);
  }
}

public class BillMap : EntityTypeConfiguration<Bill> {
  public BillMap() {
    this.HasKey(x => x.Id);

    this.HasRequired(x => x.Contract);
    this.HasMany(x => x.PaymentRequests)
        // change this to .WithOptional( x => x.Bill )
        .WithOptional(x => x.Bill);
  }
}

public class PaymentRequestMap : EntityTypeConfiguration<PaymentRequest> {
  public PaymentRequestMap() {
    this.HasKey(x => x.Id);

    this.HasRequired(x => x.Contract);
    this.HasOptional(x => x.Bill);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM