Raw SQL with Entity Framework


1 min read

Here is how to execute a raw SQL query. Since Entity frame uses reflections, you have to create some nested class so that properties can be bound to it.

class alertsType
    public long alertResponderId { get; set; }
    public int alertCount { get; set; }
    public int addressedCount { get; set; }

Then you can use the dbContext to query the database.

using (var db = new dbContext())
    var alertQuery = "SELECT * from alerts a WHERE a.UserID = @UserId and a.Date > DATEADD(DD, -30, GETDATE ))  group by [Id]";
    var alertSummary = db.Database.SqlQuery<alertsType>(alertQuery, new SqlParameter("UserId", userSession.UserID)).ToList();