简体   繁体   English

在实体框架的模型定义函数中定义子查询

[英]Define a sub-query in a Model-Defined Function in Entity Framework

Is is possible to define a subquery in a Model-Defined Function in Entity Framework? 是否可以在实体框架的模型定义函数中定义子查询? We have a situation where we have a customer object that has a history of names in an another table. 在这种情况下,我们有一个客户对象,该客户对象在另一个表中具有名称历史记录。 We want to return the most current name as part of that customer object. 我们希望返回最新名称作为该客户对象的一部分。

The model-defined function might look something like this: 模型定义的函数可能看起来像这样:

<Function Name="CurrentName" ReturnType="Edm.String">
   <Parameter Name="e" Type="Model.Customer"/>
   <DefiningExpression>
      (select top(1) n.LegalName from Entities.CustomerNames as n order by n.EffectiveDate Desc )
  </DefiningExpression>
  </Function>

Unfortunately, the above doesn't work. 不幸的是,以上方法不起作用。 We get an error of: 我们收到以下错误:

The result type 'Edm.String' specified in the declaration of the function 'SNCCModel.CurrentLegalName' does not match the result type 'Transient.collection[Transient.rowtype(LEGAL_NAME,Edm.String(Nullable=True,DefaultValue=,MaxLength=512,Unicode=False,FixedLength=False))]' of the function definition 函数“ SNCCModel.CurrentLegalName”的声明中指定的结果类型“ Edm.String”与结果类型“ Transient.collection [Transient.rowtype(LEGAL_NAME,Edm.String(Nullable = True,DefaultValue =,MaxLength = 512,Unicode = False,FixedLength = False))]'的函数定义

Any suggestions? 有什么建议么? Is this supposed to work? 这应该工作吗? Sorry, but refactoring our data model to store the most recent name in the customer table is not an option. 抱歉,但是不能重构数据模型以在客户表中存储最新名称。

Thanks, Rick 谢谢,瑞克

try the following query: 请尝试以下查询:

ANYELEMENT(select VALUE top(1) n.LegalName from Entities.CustomerNames as n order by n.EffectiveDate Desc ) ANYELEMENT(从Entities.CustomerNames中选择VALUE top(1)n.LegalName为n顺序,由n.EffectiveDate Desc表示)

Basically the query was returning a collection of rows, and expected result type is String. 基本上,查询返回的是行的集合,预期结果类型为String。 By specifying select VALUE, you get rid of the row (and project just collection of strings), and by wrapping it all in ANYELEMENT, you flatten the structure and return just single element from the result collection (in this case, the only element). 通过指定select VALUE,您可以摆脱该行(并投影只是字符串的集合),并将其全部包装在ANYELEMENT中,可以展平结构并仅从结果集合中返回单个元素(在这种情况下,是唯一的元素) 。

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

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