【问题标题】:Linq query to include a subtype包含子类型的 Linq 查询
【发布时间】:2009-04-07 19:46:04
【问题描述】:

在我的模型中,Address 作为基类,MailingAddressEmailPhone 作为 Address 的子类。 Person 有一个地址,因此查询拥有奥克兰邮寄地址的人如下所示:

var peopleInOakland = from p in entities.DbObjectSet.OfType<Person>()
                             from a in p.Addresses.OfType<MailingAddress>()
                             where a.City == "Oakland"
                             select p;

如何在我的查询结果中也包含此人的邮寄地址?我知道我应该使用 Include,但我不确定如何在 .Include 参数中命名 MailingAddress

提前致谢

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    您必须创建一个具有您正在寻找的特定类型的新类型,如下所示:

    var peopleInOakland = 
        from p in entities.DbObjectSet.OfType<Person>()
        from a in p.Addresses.OfType<MailingAddress>()
        where a.City == "Oakland"
        select 
            new { Person = p, Addresses = p.Addresses.OfType<MailingAddress>() };
    

    【讨论】:

      【解决方案2】:

      只需使用理解表达式的本地名称选择匿名类型:

      ...
      select new {
        Persion = p,
        Address = a
      };
      

      【讨论】:

      • 我认为他要求使用语法来填充使用 MailingAddress 类型的地址返回的 Person 对象。也就是说,我不知道该怎么做:)
      • @Jonathan:如果正确,那么这是对任一答案的微不足道的修改,但需要澄清;正如两个答案都“在查询结果中包含邮寄地址[...]”
      猜你喜欢
      • 1970-01-01
      • 2020-04-17
      • 2012-04-16
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多