I want to use a SQL query in Entity Framework.
Here is my code:
string sql = (@"SELECT G.GainId,
(SELECT Name FROM Carrier WHERE CarrierId = G.CarrierId) AS Carrier,
(SELECT Name + ' ' + Surname FROM [User] WHERE UserId = G.GainerId) AS Gainer,
(SELECT Name + ' ' + Surname FROM [User] WHERE UserId = G.GiverId) AS Giver,
(SELECT Name + ' ' + Surname FROM [User] WHERE UserId = G.CustomerId) AS Customer,
P.Name,
G.Gained,
G.Paid
FROM Gain AS G
INNER JOIN Product AS P ON P.ProductId = G.ProductId");
DataTable tbl = _context.Database.SqlQuery<DataTable>(sql) as DataTable;
But tbl is null. Do you have any suggestions? I am new with Entity Framework.
That’s because
SqlQueryis not meant to return aDataTable. It’s built to return your entity types as anIEnumerable<T>whereTis your entity type. Use the below statement and remember that it’s an enumerable type that’s being returned. Now perform with it what you need.Edited
Yes, in fact you can very easily build this type. In fact, because the query seems so isolated you could probably build a private class inside of the class it’s executed in so that how I’ll build the example. However, that’s something you need to decide. Below I’ll give you a template for the class. The two properties with
??I don’t know exactly what type they correlate to so you’ll need to plug those in.And then issue the statement like this…