转换为派生类中的LINQ to实体表每层次继承查询 [英] Casting to a derived type in a LINQ to Entities query with Table Per Hierarchy inheritance

查看:131
本文介绍了转换为派生类中的LINQ to实体表每层次继承查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ到实体模型表每层次继承。我有过基本类型的查询,而我想要做的具体类型相关的逻辑。例如:

 的IQueryable<基本类型>基地= ...

//这工作正常
变种结果= base.Select(二=> b为DerivedType1?1:2).ToList();

//这不会编译到SQL
VAR结果2 = base.Select(B => b为DerivedType1((DerivedType1)B).DerivedProperty:空).ToList();
 

有没有办法做这样的事情,而不用单独处理每个派生类型的IQueryables:

  //我宁愿不这样做:
VAR resultA = base.OfType< D​​erivedType1>()选择(D => d.DerivedProperty);
VAR resultB = base.OfType< D​​erivedType2>()选择(D =>默认值(INT)?);
VAR的结果= resultA.Concat(resultB).ToList();
 

解决方案

直接铸像实体类型(DerivedType1)乙不支持使用LINQ于─实体但操作符( B为DerivedType1 )的,因此你可以尝试:

  VAR结果2 =基地
    。选择(B => b为DerivedType1
        ? (二为DerivedType1).DerivedProperty
        : 空值)
    .ToList();
 

I have a LINQ to entities model with Table Per Hierarchy inheritance. I have a query over the base type, and I want to do specific type-dependent logic. For example:

IQueryable<BaseType> base = ...

// this works fine
var result = base.Select(b => b is DerivedType1 ? 1 : 2).ToList();

// this doesn't compile to SQL
var result2 = base.Select(b => b is DerivedType1 ? ((DerivedType1)b).DerivedProperty : null).ToList();

Is there any way to do something like this without processing IQueryables of each derived type separately:

// I'd rather not do this:
var resultA = base.OfType<DerivedType1>().Select(d => d.DerivedProperty);
var resultB = base.OfType<DerivedType2>().Select(d => default(int?));
var result = resultA.Concat(resultB).ToList();

解决方案

Direct casting to an entity type like (DerivedType1)b isn't supported with LINQ-to-Entities but the as operator (b as DerivedType1) is, hence you could try:

var result2 = base
    .Select(b => b is DerivedType1
        ? (b as DerivedType1).DerivedProperty
        : null)
    .ToList();

这篇关于转换为派生类中的LINQ to实体表每层次继承查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆