【问题标题】:Get list of parent sub-type with all sub-type in LINQ获取 LINQ 中所有子类型的父子类型列表
【发布时间】:2017-11-09 19:54:34
【问题描述】:

首先在 C# 代码中使用许多具有零一关系的子类型表!

 public class MemberContractRelation
{
    [Key]
    public long Id { get; set; }
    public long ContractId { get; set; }
    public long MemberId { get; set; }
    public long ListPrice { get; set; }
    public decimal TaxCountryToPay { get; set; }
    public decimal TaxProvinceToPay { get; set; }
    public long InsuredCode { get; set; }

}


 public class FamilyMemberContractSubtype : MemberContractRelation
{
    public long CalculatedCheckupPrice { get; set; }

}

我想通过此代码获取带有子类型相关记录(如左连接)的父表(MemberContractRelation)列表:

 var familyMemberContractSubtype = _rep.FamilyMemberContractSubtype.Where(a => a.Id == ContractId).Select(x => new
          FamilyMemberInformationsBag
        {
            BirthDate = x.Member.BirthDate,
            FirstName = x.Member.FirstName,
            LastName = x.Member.LastName,
            NationalID = x.Member.NationalCode,
            PhoneNumber = x.Member.IranPhoneNumber,
            Price = x.ListPrice,
            ChekUpPrice = x.CalculatedCheckupPrice,
            TotalPrice = x.ListPrice + x.CalculatedCheckupPrice + x.TaxProvinceToPay + x.TaxCountryToPay,
            TaxProvinceToPay = x.TaxProvinceToPay,
            TaxCountryToPay = x.TaxCountryToPay

        }).ToList();

但它只返回具有子类型的记录,而不返回 MemberContractRelation 中的其他记录! 我想获取具有子类型的 MemberContractRelation 列表,如果它没有记录在子类型中,则返回子类型中属性的 Null 值!

请记住,除了上述解决方案之外,我不能为我的项目使用任何其他解决方案!

【问题讨论】:

  • 这听起来像 TPT EF 继承模式,对吗?
  • 是的,类似的,但我不知道 TPT 的详细信息

标签: c# sql entity-framework linq code-first


【解决方案1】:

假设这是使用 EF TPT 继承策略(看起来),首先您应该从父(基)表开始查询:

// instead of _rep.FamilyMemberContractSubtype
// assuming _rep is DbContext
_rep.Set<MemberContractRelation>()

然后使用运算符as(重要:不强制转换!)访问子类型成员,将不可为空的类型提升为可空。在您的示例中:

ChekUpPrice = (long?)(x as FamilyMemberContractSubtype).CalculatedCheckupPrice

TotalPrice = x.ListPrice + x.TaxProvinceToPay + x.TaxCountryToPay +
    ((long?)(x as FamilyMemberContractSubtype).CalculatedCheckupPrice ?? 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多