0

How can I execute a raw SQL query which returns an anonymous type?

I also followed msdn link, but I couldn't find any solution for using DbContext.

Thanks in advance.

I resolved the issue. First I converted my DbContext Object to ObjectContext object. Then rest is same as per above link.

some code snippet

// convert DbContext to ObjectContext.
var objContext = new DBEntities(); // db context object
var adapter = (IObjectContextAdapter)objContext;
var objectContext = adapter.ObjectContext;

ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(sqlQuery, objectContext);
Rakesh Jena
  • 159
  • 1
  • 8
  • Use dynamic instead, as I read from this post you can't do Anonymous http://stackoverflow.com/questions/29852912/return-anonymous-type-using-sqlquery-raw-query-in-entity-framework – believe me Mar 04 '16 at 17:43
  • 1
    It is very well explained in the link you provided how to call the context object and use it to return anonymous results, what's the problem exactly ? – Antoine Pelletier Mar 04 '16 at 18:11
  • @Antoine have you tried? I have tried and I am getting error since I am using DBContext object. – Rakesh Jena Mar 05 '16 at 05:27
  • @believe my query is a dynamic string and it returns different result set at every execution. I can't have a specific type to catch the result set. Can you give some code snippet. – Rakesh Jena Mar 05 '16 at 05:32
  • What kind of error ? Would you put it in your question, with the part of your code that trows errors ? Maybe it's just your connection string (but i don't think it's your case) and also, have you tried doing it like @The Anathema, i always do just like him.. so i never had this context problem – Antoine Pelletier Mar 07 '16 at 15:51
  • I resolved the issue. I converted my DbContext to ObjectContext. – Rakesh Jena Mar 08 '16 at 06:14

1 Answers1

1

Just project it.

using (var context = new DbContext())
{
    var names = context.Employees.Select(e => new { Name = e.Name });
}

Or

using (var context = new DbContext())
{
    ObjectQuery<DbDataRecord> query =
         context.Employees.Select("it.Name");

    foreach (DbDataRecord record in query)
    {
         // iterate over records
    }
}
Frozenthia
  • 759
  • 3
  • 9