I am making project in asp.net 6 mvc, and i have to execute complex query contain joins, union and all. I want to fetch data from the database. How to do that through "FromSqlRaw"?
We can fetch data through ‘FromSqlRaw’ from a single table but how to do it if we are fetching data from multiple tables and using joins, union
2
Answers
You Can Use Dapper as M/ORM to connect to database and query to it. if you want to select you can use this Code:
if you want to execute something like Update, Put or some SP you have to use this code :
by the way, You have to Get Dapper Nuget Package.
Well, based on your scenario and description, it seems that you would like to execute complex query which involved lot of SQL JOIN, Union even other SQL functionalities, actually, there might numerous way to implement that, but using SQL views upon your Entity context would be more easier and convenient to execute join and other query, no mater how complex it is.
In order to do that, you can create a SQL view, the query you would like to write including all of your requirements, then this view would return your expected entity field or property your can say, now create a class based on the field or property you have returned within your view. Finally, introduce that class as
DbSet<YourClass>
in your dbContext,Now you can, call it from your controller using
FromSqlRaw
and you can set any conditional on your View.Let’s have a look in practice how we can implement in code snippet,
SQL View:
This should looks like as following:
Demo Class:
DbContext:
Controller:
Note: Set additional condition here in
sqlQuery
variable in order to keep clean your view. In addition, property name should be unique and duplicate property name should used Alias and use alias name in C# property.Output: