Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i return a dataReader using Entity Framework 6.1?

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.

like image 791
Gillardo Avatar asked Nov 04 '25 01:11

Gillardo


1 Answers

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();
like image 146
DavidG Avatar answered Nov 06 '25 16:11

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!