显式变量声明

时间:2019-01-17 00:59:02

标签: c# entity-framework syntax variable-declaration

我有一个隐式定义为var的局部变量,并且正在填充通过实体框架从数据库检索的对象。当我将鼠标悬停在变量上时,将获得详细信息,如下图所示。

enter image description here

如何在不使用var的情况下显式定义变量,例如

IQuerable<{Inpection Ins, Field F}> tempInspInner =  getInspections();

代替:

var tempInspInner =  getInspections();

更新

getInspections()具有以下代码:

return _dbcontext.Inspection
                .Join(_dbcontext.Field,
                ins => ins.FieldId,
                f => f.FieldId,
                (ins, f) => new { Ins = ins, F = f }).Where(*hidden*);

2 个答案:

答案 0 :(得分:2)

getInspections返回一个匿名类型(meh sigh ),名称为tuples不会帮助您,但是您可以将其投影到类中

public class SomeObject 
{
    public Inpection Ins {get;set;}
    public Field F {get;set;}
}

IQueryable<SomeObject> = getInspections.Select(x => new SomeObject { Ins = x.Ins, F = x.F });

这样一来,您最好还是返回一个强类型的IQueryable

答案 1 :(得分:1)

正如其他人所述,理想的选择是让getInspections()返回一个强类型的集合。

作为替代方案,您应该能够使用显式类型(使用named tuples)来定义变量,如下所示:

IEnumerable<(Inspection Ins, Field F)> test = getInspections()
    .AsEnumerable()
    .Cast<dynamic>()
    .Select(x => (Ins: (Inspection)x.Ins, F: (Field)x.F));

此方法的一个缺点是,由于将结果强制转换为dynamic,因此编译器将不知道所使用的源属性(x.Insx.F)是否发生了变化。因此,在运行时执行该操作之前,您将不知道这是行不通的。