How to convert sql query into Linq to entities? - sql-server

I am new to joins in linq to entities. I have one query in sql server and want to convert it into LINQ to Entities.
Can someone please provide the solution for the same? Do we have any online tool to convert sql queries to LINQ to entities?
SELECT R.ID,r.Name,u.UserId
FROM Roles R
Left JOIN UserRoles U ON r.Id = u.RoleId
AND [UserId] = '5'
where [UserId] IS NULL

DefaultIfEmpty will result in a left outer join, therefore as you want a simple left join you should do as follows:
var list = (from r in context.Roles
join u in context.UsersRoles on r.Id equals u.RoleId && u.UserId='5' into x
where r.UserId == null
select new
{
r.Id,
r.Name,
u.UserId
}).ToList();

var list = (from r in context.Roles
join ur in context.UsersRoles on r.Id equals ur.RoleId && ur.UserId='5' into x
from y in x.DefaultIfEmpty()
where r.UserId ==null
select new Object
{
Id = r.Id,
Name = r.Name,
ur.UserId
}).ToList();
Note: Not understand your second UserId IS NULL logic

Related

need to convert posted sql query to LINQ

How do i make that query in linq please advise
select *
from tblPermission
where RoleId in (select roleid from tbluserrole where userid = #userID)
When converting from SQL to LINQ, convert in the order of the LINQ phrases. If your SQL has table aliases, use them as the range variables. If a query contains a sub-query, translate it first in the same way. Translate IN into Contains.
var roles = from ur in tbluserrole where ur.userid == parmUserId select ur.RoleId;
var ans = from p in tblPermission
where roles.Contains(p.RoleId)
select p;
You can do this in 2 ways:
var roles = tbluserrole.Where(e => e.userid == userId).Select(e => e.roleid).ToList();
var prmsns = tblPermission.Where(e => roles.Contains(e.RoleId).ToList()
or
var prmsns = (from e in tblPermission
let roles = tbluserrole.Where(f => f.userid == userId).Select(f =>
f.roleid).ToList();
where roles.Contains(e.RoleId)
select e).ToList();
from
EDIT:
you can do this with inner join like this
var prmsns = (from e in tblPermission
join f in tbluserrole on tblPermission.RoleId equals tbluserrole.roleid
where f.userId == userId
select e).ToList();

Converting SQL inner join, group by and order to LINQ

I have created an SQL query as follows:
SELECT s.FullName, s.[Id], COUNT(t.[User]) AS Records
FROM dbo.AspNetUsers s INNER JOIN dbo.PBBuilds t
ON s.Id = t.[User]
GROUP BY t.[User], s.[FullName], s.[Id]
ORDER BY COUNT(t.[User]) DESC
I'm attempting to convert this to a LINQ query, and this is how far i have got:
Dim results = From H In context.Users
Join C In context.PBBuilds On H.Id Equals C.User
Group By C.User Into
Could anyone please advise.
Try this query -- (make changes accordingly though)
var results = From U In context.AspNetUsers
Join P In context.PBBuilds On U.Id Equals P.User
Group By new { P.User, U.FullName } Into g
Orderby COUNT(P.User) Descending
select new {
FullName = U.FullName,
ID = U.Id,
Records = COUNT(P.User)
};
try code
var results = From U In context.AspNetUsers
Join P In context.PBBuilds On U.Id Equals P.User
Group new {U,P} By new { P.User, U.FullName } Into g
select new {
FullName = g.FirstOrDefault().U.FullName,
ID = g.FirstOrDefault().U.Id,
Records = g.Count()
}).OrderByDescending(c=>c.Records).ToList();

SQL Server 2008: Only one result, joining 3 tables

I have the following databases:
IMAGE UPDATED
SELECT
l.FECHA, nc.IdNumeroControlTrabajador AS ENLACE,
t.RFC, t.Homonimia AS HOM,
t.ApellidoPaterno, t.ApellidoMaterno,
t.Nombre, l.IMPORTE,
cp.NombreOrgano AS DEPENDENCIA, l.OBSERVACIONES,
l.FECHA_INICIAL, l.FECHA_FINAL,
MAX (cn.FechaIngresoGobierno)
FROM
CapturaFAIFAP.dbo.Laudos AS l
LEFT JOIN FAIFAPparalelo.dbo.NumeroControlTrabajadores AS nc ON l.ID = nc.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.ClaveNominalTrabajadores AS cn ON l.ID = cn.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.Trabajadores AS t ON l.ID = t.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.ClaveProgramatica AS cp ON cn.idClaveProgramatica = cp.idClaveProgramatica
LEFT JOIN (
SELECT
cp.NombreOrgano,
MAX (cnt.FechaIngresoGobierno) AS fecha
FROM
FAIFAPparalelo.dbo.ClaveNominalTrabajadores as cnt
GROUP BY
cp.NombreOrgano
) AS j ON (
cp.NombreOrgano = j.NombreOrgano
AND j.fecha = cn.FechaIngresoGobierno
)
GROUP BY
l.FECHA, nc.IdNumeroControlTrabajador, t.RFC,
t.Homonimia, t.ApellidoPaterno, t.ApellidoMaterno,
t.Nombre,l.IMPORTE,cp.NombreOrgano,l.OBSERVACIONES,
l.FECHA_INICIAL,l.FECHA_FINAL,cn.FechaIngresoGobierno
I need to unify the query. The huge query i put in code, and a similar query in the image. If i join the tables ClaveNominal and ClaveProgramatica i have duplicities, because sometimes the persons have 2 ClavesProgramaticas, due to the system I use, not delete or update the current registry, just puts in inactive and adds a new one active, and i can't make the condition to activo because, that represents if the person still works here.

Can I apply join on four tables or anything similar in Entity Framework?

I have four tables
Users
{
PK: UserId
...
}
Products
{
PK: ProductId
FK: UserId
...
}
ProductTags
{
PK: ProductTagId
FK: ProductId
...
}
LikedProducts
{
PK: Id
UserId
ProductId
...
}
Here is my query.
int userId = 1; //It will be different for different user.
var tblProductList = (from t in repo.ProductTags
join p in repo.Products on t.ProductId equals p.ProductId
join u in repo.LikedProducts on p.UserId equals u.UserId
join l in repo.LikedProducts on new { p.ProductId, userId } equals new { l.ProductId, l.UserId }
where productIdList.Contains(p.ProductId)
select p
).ToList();
I am getting The type of once reference in join clause is incorrect error.
I am getting list of ProductId let's say productListIds from azure search. My question is, Is it possible to get some column(Not all data) from each table using single query either by Join or using Entity Framework.
I googled It but didn't find any solution in which we could apply Join more than 3 tables.
Thanks in advance.
I am still unsure as to what you are trying to extract. Here is a corrected query though as you were using LikedProducts twice which is not necessary.
This would get a list of products that the user likes and products that have a tag (through the inner join):
var tblProductListOfLikedProductsForUser = (from p in repo.Products
join tag in repo.ProductTags on p.ProductId equals tag.ProductId // as you are not retrieving tag info this is only usefull if you want to ensure that each product has a tag
join l in repo.LikedProducts on new { p.ProductId, userId } equals new { l.ProductId, l.UserId } // limits products to those the user likes
// join u in repo.Users on l.UserId equals u.UserId // no benifit in using Users if you dont want user info and already have a userid
where productIdList.Contains(p.ProductId)
select p).ToList();
If productId and UserId data exist than return true otherwise false).
Here is a modified query that would return a list of product ids for those that the user likes and are in the list. The joins would only ensure that the product exists in all the tables (i have no idea what the referential integrity is of the db, if there are FK constraints defined you can get rid of the join on products).
var productIdsLikedProductsForUser = (from p in repo.Products // ensure the product exists
join tag in repo.ProductTags on p.ProductId equals tag.ProductId // ensure the product has a tag
join l in repo.LikedProducts on new { p.ProductId, userId } equals new { l.ProductId, l.UserId } // limits products to those the user likes
where productIdList.Contains(l.ProductId)
select l.ProductId).ToList();
If you do not care about that then you do not need a complex join, just query the LikedProducts table directly.
var productIdsLikedProductsForUser = (from l in repo.LikedProducts
where productIdList.Contains(l.ProductId)
&& l.UserId == userId
select l.ProductId).ToList();
As Products table contains UserId(FK reference of Users table) so Is it possible to include UserName, FirstName, LastName from Users Table?
Yes, you can use a group by clause.
var userWithLikedProducts = (from l in repo.LikedProducts
join u in repo.Users on l.UserId equals u.UserId
where productIdList.Contains(l.ProductId)
&& l.UserId == userId
group l.ProductId by new { u.UserName, u.FirstName, u.LastName } into productGroup
select new { User = productGroup.Key, LikedProductIds = productGroup.Select(x => x) }).SingleOrDefault();

Showing NULL values in SQL Server Joins

I'm using SQL Server. I've 3 tables :
tblUser
tblAudit
tblEnum
The tblAudit has got 4 columns :
nUserId, nID: These two columns point to the tblUser
vFromValue, vToValue: These two columns point to the tblEnum
Now, I need to show the actual values from the tblUser and tblEnum based on the IDs present in the tblAudit table.
The query that I have written looks something like this :
SELECT A.aEventID,
U.tName AS MakerChecker,
U2.tName AS OnUser,
VLE.tDisplayName AS FromValue,
VLE2.tDisplayName AS ToValue,
A.dChangeTime AS Timestamp
FROM tblAudit A INNER JOIN tblUser U ON A.nUserId = U.aUserId
INNER JOIN tblUser U2 ON A.nID = U2.aUserId
INNER JOIN tblEnum VLE ON A.vFromValue = VLE.nIndex OR (A.vFromValue IS NULL)
INNER JOIN tblEnum VLE2 ON A.vToValue = VLE2.nIndex OR (A.vToValue IS NULL)
Because the values in the Audit table is null for the columns vFromValue and vToValue for some rows, those values are not coming as NULL but the previous value.
How can I display the null values intact by changing the above query? Please help.
Since the tblAudit.vFromValue and tblAudit.vToValue have NULLs, try this:
SELECT A.aEventID,
U.tName AS MakerChecker,
U2.tName AS OnUser,
VLE.tDisplayName AS FromValue,
VLE2.tDisplayName AS ToValue,
A.dChangeTime AS Timestamp
FROM
( SELECT aEventID, nUserId, nID, dChangeTime
, COALESCE(vFromValue, -9999) AS vFromValue --- some non-existent
, COALESCE(vToValue, -999) AS vToValue --- value
FROM tblAudit
) AS A
INNER JOIN tblUser U
ON A.nUserId = U.aUserId
INNER JOIN tblUser U2
ON A.nID = U2.aUserId
LEFT JOIN tblEnum VLE
ON A.vFromValue = VLE.nIndex
LEFT JOIN tblEnum VLE2
ON A.vToValue = VLE2.nIndex
or this:
SELECT A.aEventID,
U.tName AS MakerChecker,
U2.tName AS OnUser,
( SELECT VLE.tDisplayName
FROM tblEnum VLE
WHERE A.vFromValue = VLE.nIndex
) AS FromValue,
( SELECT VLE2.tDisplayName
FROM tblEnum VLE2
WHERE A.vToValue = VLE.nIndex
) AS ToValue,
A.dChangeTime AS Timestamp
FROM tblAudit AS A
INNER JOIN tblUser U
ON A.nUserId = U.aUserId
INNER JOIN tblUser U2
ON A.nID = U2.aUserId
If I understand your question-- try use LEFT JOIN for your two last rows (and delete conditions after OR).

Resources