简体   繁体   English

如何从EF SQL查询返回匿名类型

[英]How to return anonymous type from EF sql query

var results = ObjectContext.ExecuteStoreQuery<T>("exec MyStoredProc");

The MyStoreProc returns 1 row always with 9 columns that are all int. MyStoreProc总是返回1行,其中9列都是int的。

I don't want to create a class or struct for this one-time use type data. 我不想为此一次性使用类型数据创建类或结构。

What would be the cleanest way to do this WITHOUT creating a class? 如果不创建类,最干净的方法是什么?

Theoretically, you could create a generic wrapper method that implicitly detects the <T> type based on a sample value that you pass in, and then pass it an example of the anonymous structure you expect to get back. 从理论上讲,您可以创建一个通用包装方法,该方法根据传入的样本值隐式检测<T>类型,然后将其传递给您希望返回的匿名结构的示例。 You could call it like this: 您可以这样称呼它:

var results = AnonymousQueryWrapper("exec MyStoredProc", new {id = 0, name = "", ...});

However, I'd say creating a private class is not much more burdensome, and is much clearer. 但是,我要说的是创建一个私有类并不会带来太多负担,而且会变得更加清晰。 So when you ask "What would be the cleanest way to do this?" 因此,当您问到“最干净的方法是什么?” I have to answer, "Create a named type". 我必须回答“创建命名类型”。

It appears that EF doesn't support returning any types other than ones that have EF mappings when using the ObjectContext.ExecuteStoreQuery() method. 似乎在使用ObjectContext.ExecuteStoreQuery()方法时,除具有EF映射的类型外,EF不支持返回任何其他类型。

I ended up using a SqlCommand object and datareader with an anonymous type. 我最终使用了带有匿名类型的SqlCommand对象和datareader。

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

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