简体   繁体   English

在LINQ查询(EF 5)中包括编码字段值

[英]Include coded field value in LINQ query (EF 5)

Not sure of the correct terminology, but is there any way to include a "coded field" that doesn't exist in the table, in an Entity Framework 5 LINQ query? 不确定正确的术语,但是在Entity Framework 5 LINQ查询中,是否有任何方法可以包含表中不存在的“编码字段”?

For example, in SQL you can do this: 例如,在SQL中,您可以执行以下操作:

SELECT 'Ledger' AS type, (...) FROM table

So that the query result includes a field called 'type' with the value 'Ledger'. 这样查询结果将包括一个名为“ type”的字段,其值为“ Ledger”。 Is there a way to do this in a LINQ query? 有没有办法在LINQ查询中做到这一点?

And before you ask why it has to be in the query, it's because the query is a union of multiple tables and I need a designation of which table the data came from. 在询问为什么必须在查询中之前,这是因为查询是多个表的联合,并且我需要指定数据来自哪个表。 Without this I will need to query each one separately then merge them. 没有这个,我将需要分别查询每个人,然后将它们合并。

Sure, you can. 你当然可以。 It would look a bit like this: 它看起来像这样:

var results = dbContext.Table.Select(r => new { type = "Ledger", ... });

Or if you need a named type, something like this should work: 或者,如果您需要命名类型,则应执行以下操作:

public class UnionResult 
{
    string Type { get; set; }
    ...
}

var results = dbContext.Table.Select(r => new UnionResult { Type = "Ledger", ... });

Yes, you can totally do this. 是的,您完全可以做到这一点。

pswg has used something that is called an anonymous type. pswg使用了一种称为匿名类型的东西。 Basically you define the outcome of the query on the fly. 基本上,您可以动态定义查询的结果。 As you can see in his answer, in expression syntax this looks like Select(r => new { type = "Ledger", ... }); 如您在他的答案中所见,在表达式语法中,这看起来像Select(r => new { type = "Ledger", ... });

In query syntax it looks like this: 在查询语法中,它看起来像这样:

from xxx in y
select new { type = "Ledger" };

Behind new, there is no class / type or anything. 在new的后面,没有class / type或任何东西。 Neither is type defined. 两者均未定义类型。 But it will compile as a string natuarlly. 但是它会自然地编译为字符串。

On the other hand you can define a custom ViewModel class for this 另一方面,您可以为此定义一个自定义ViewModel类

public class CustomResultVM
{
   //ignoring getter and setter
   public int Id;
   public string type;
   public string name;
}

your select would now be strongly typed and look like this: 您的选择现在将被强类型键入,如下所示:

Select(r => new CustomResultVM 
{ 
  Id = r.xxx,
  type = "Ledger", 
  Name = r.xxxx 
});

//query snytax
from xxx in y
select new CustomResultVM 
       {
          Id = r.xxx,
          type = "Ledger", 
          Name = r.xxxx 
       };

both ways are valid and it depends on what you need at any given point and time. 两种方法都是有效的,并且取决于您在任何给定时间点的需求。

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

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