how can I run a raw sql query in asp.net mvc.
I know how to write the query, but dont know how to execute it and return the query data to the view. The query contains data from multiple tables. I specifically need help with displaying the results in the view.
18 Replies
ASP.NET doesnt talk with database on its own, so what are you using to communicate with the database? SqlConnection? EF? Dapper?
and you say that you specifially need help with displaying the results, does that mean you've successfully managed to execute the query?
Ef
i leanrt i could use a sql query string and then do from sql (string)
i jsut dont know how to display on view
you really shouldnt be using raw sql queries with EF unless its unavoidable
ight how come should i use linq i jsut prefer sql
is it not possible
Because you lose all kind of type safety and you bypass EF
like, why bother using EF at all if you want to write your SQL yourself? use dapper then
true
absolutely nothing wrong with handwriting SQL, but if thats what you want, use the right tools for that
which imho is dapper
but what i am sturgling with is i dont get to hwo to make a query in linq that returns mutiple results to a view
multiple results? as in just more than one row?
like a list say i wnat to selct level and subejcts
yes like not jsut the sum of the total vlaues
yeah thats fine, you just use
.ToListAsync()
yes but in the view what model do i base it off
var results = await context.Levels.Where(x => x.Something).ToListAsync();
boom donedo i need to create a sperate vm
if i have data form diffrent tables
yeah, you should project your query results to a "DTO" model
oh ok that makes senes
thank you very much
enjoy the rest of your day
something like this
Depending on your use case, Dapper might be a great option for you in the future if you find you still prefer sql over linq