简体   繁体   中英

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

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 )

Basically the query was returning a collection of rows, and expected result type is 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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