Srikant Sahu Srikant Sahu - 6 days ago 6
C# Question

How to call raw SQL queries in EF 6.0

I have a simple gridview which I need to bind with a list of users.

In EF.5.0 I could simple write

context.Users.Select(emp => new { Name = emp.FirstName, EmailId = emp.EmailId, UserId = emp.UserId }).ToList();


However, I don't see the
.ToList()
method anymore in EF6.0

So, I have to write an async query using
ToAsyncList()
. However, not sure why the below code does not work and system goes in endless execution.

protected void Page_Load(object sender, EventArgs e)
{
var task = LoadData();
task.Wait();
GridView1.DataSource = task.Result;
GridView1.DataBind();
}

private async Task<List<User>> LoadData()
{
List<User> users = null;

using (var context = new BlogEntities())
{
users = await context.Database.SqlQuery<User>("Select * from User", new object[] { }).ToListAsync();
}

return users;
}


Can anyone please let me know, what I am doing wrong here?

Answer

Use this code:

var users = context.Users.SqlQuery("SELECT * FROM dbo.User").ToList();

Comments