user3953989
user3953989

Reputation: 1929

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.

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?

Upvotes: 2

Views: 2301

Answers (2)

user3953989
user3953989

Reputation: 1929

It appears that EF doesn't support returning any types other than ones that have EF mappings when using the ObjectContext.ExecuteStoreQuery() method.

I ended up using a SqlCommand object and datareader with an anonymous type.

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156459

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. 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".

Upvotes: 5

Related Questions