4

Exactly as the question asks. I am using entity framework for most of my code, but i also need to execute and return a count or columns from a sql table that is not within my entity framework context.

5
  • Why don't you simply use SqlConnection with your connection string? Commented Jul 10, 2015 at 8:33
  • 2
    You can still use ADO.NET Commented Jul 10, 2015 at 8:36
  • I have used SqlConnection with ado.net at the moment, but i didnt know if creating a new SqlConnection was the right thing to do? or whether there was a way i could use EF connection, as if there is a transaction running, i want to use it Commented Jul 10, 2015 at 8:40
  • Why return columns that aren't in your EF context - why not add those tables to the context? Commented Jul 10, 2015 at 8:48
  • They are dynamic tables that i have no idea look like Commented Jul 10, 2015 at 8:49

2 Answers 2

6

You can run a raw query using Entity Framework, for example:

using (var context = new BloggingContext()) 
{ 
    var blogNames = context.Database.SqlQuery<string>( 
                       "SELECT Name FROM dbo.Blogs").ToList(); 
}

If you want to return a more complex type, you can define your own class and use that instead. As long as the properties match the names of the columns you select, it will work. So lets make a class:

public class MyClass
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

And use it:

List<MyClass> result = ctx
    .Database.SqlQuery<MyClass>("SELECT Id, UserName FROM dbo.Users")
    .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

But how would you return multiple columns? All different data types?
You can make your own non-entity class and use it. Check my edit.
Problem is that I cannot make a class because the table is dynamic and i do not know this at design time. I do have the metadata of the column names at runtime
1

The whole point of an IDataReader is to Cursor through the data as it is being returned over the wire (exempli gratia TCP/IP) and thus not incur the overhead of stuffing it all into memory. If you're dealing with millions of rows, then reading everything into memory is a bad idea. If that is the case, then grab the underlying connection string from EF API and utilize ADO.NET. There's better better Aysnc support there as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.