How to convert SQL Query to Lambda Expression - sql

Here is my SQL Query:
SELECT
UserName,
IsApproved
FROM aspnet_Users u
INNER JOIN aspnet_Membership m
ON u.UserId = m.UserId
Can anybody help me how to write with lambda expression?

from u in aspnet_Users
join m in aspnet_Membership on u.UserId equals m.UserId
select new { u.UserName, m.IsApproved };

Try this..
from u in context.aspnet_Users
join m in context.aspnet_Membership on u.UserId equals m.UserId select new { u.UserName, m.IsApproved};

You can use the JOIN with Lambda Expression something like this,
var result = aspnet_Users
.Join(aspnet_Membership,
u => u.UserId,
m => m.UserId,
(u, m) => new
{
UserName = u.UserName,
IsApproved = u.IsApproved
}
);

A what about this query:
select UserName, IsApproved
from aspnet_Users u
inner join aspnet_Membership m on u.UserId = m.UserId
where u.UserName = #UserName
Where to put "where" in this case? #UserName is the string parameter that i define in
public ActionResult UserActivation(string UserName)
{
...
}

Related

How do i convert this SQL to Entity Framework LINQ query

Can someone help me convert this SQL Query to EntityFramework LINQ?
DECLARE #UserId varchar(50) = '123'
SELECT
TL.TrackId,
COUNT(*) AS LikeCount,
(SELECT IIF(COUNT(*) > 0, 'true','false') FROM UserTrackLikes WHERE
UserId = #UserId AND TrackId = TL.TrackId) AS IsLiked
FROM TrackList AS TL
LEFT OUTER JOIN UserTrackLikes AS UTL
ON UTL.TrackId = TL.TrackId
GROUP BY TL.TrackId
You can use the query syntax:
int userId = 123;
var result = (from trackList in context.TrackLists
select new
{
trackList.TrackId,
LikeCount = trackList.Likes.Count(),
IsLiked = trackList.Likes.Any(x => x.UserId == userId)
}).ToList();
Assuming that here, Likes is a collection of UserTrackLike, declared like this:
public ICollection<UserTrackLike> Likes { get; set; }

how to convert a sql query into linq LEFT OUTER JOIN

This is the SQL query that returns the data I need:
SELECT
E.DESCS AS EMP, C.USERNAME,
(SELECT A.DESCS
FROM CAD_COLABORADOR H, CAD_DEPT A
WHERE H.DEPT = A.ID AND H.ID = C.ID) AS DEPT,
D.IDENTIFICADOR, D.MODELO, O.DESCS AS OFFICE,
D.K_OFFICE AS 'KEY OFFICE', S.DESCS AS SO, D.K_SO AS 'KEY SO'
FROM
IN_DESKTOP D
LEFT OUTER JOIN
CAD_COLABORADOR C ON D.ID = C.DESKTOP
INNER JOIN
CAD_EMP E ON D.EMP = E.ID
INNER JOIN
CAD_OFFICE O ON D.V_OFFICE = O.ID
INNER JOIN
CAD_SO S ON D.V_SO = S.ID ;
This is the linq expression I'm using plus has some inconsistencies since it returns the most data are not exactly the same as the SQL query:
var result = from desk in db.IN_DESKTOP
join co in db.CAD_COLABORADOR on desk.id equals co.id into egroup
from co in egroup.DefaultIfEmpty()
join e in db.CAD_EMP on desk.emp equals e.id
join o in db.CAD_OFFICE on desk.v_office equals o.id
join s in db.CAD_SO on desk.v_so equals s.id
select new
{
Empresa = e.descs,
UserName = co.username,
Departamento = co.CAD_DEPT.descs,
Identificador = desk.identificador,
Modelo = desk.modelo ,
Offices = o.descs,
KeyOfice = desk.k_office,
KeySo = desk.k_so
};
A left outer join in C# is just a GroupJoin followed by a SelectMany with default if empty - I've been using this extension for lambda expressions
public static class LinqExtension
{
public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
this IEnumerable<TLeft> leftCollection, IEnumerable<TRight> rightCollection,
Func<TLeft, TKey> leftKey, Func<TRight, TKey> rightKey,
Func<TLeft, TRight, TResult> result)
{
return leftCollection.GroupJoin(rightCollection,
leftKey,
rightKey,
(leftObject, rightObject) => new { leftObject, rightObject })
.SelectMany(x => x.rightObject.DefaultIfEmpty(),
(l, r) => new { left = l.leftObject, right = r })
.Select(x => result.Invoke(x.left, x.right));
}
}

How to join two tables?

Feedback
User
This query works.Fetching datas in feedback table:
public function feedback_data()
{
$recipe_id = 0;
$this->db->where('recipe_id',$recipe_id);
$query = $this->db->get('feedback');
return $query->result_array();
}
I need to fetch feedback_id and comment from feedback table and firstname and lastname from user table where user_id from feedback is equal to user_id from user. By the way, here's my query and i think it's not working.
$this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
$this->db->from('feedback f')
$this->db->join('user u','u.user_id = f.user_id');
$this->db->where('f.recipe_id', $recipe_id);
$query = $this->db->get()->result();
return $query;
Please try this :
$this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
$this->db->from('feedback f')
$this->db->join('user u','u.user_id = f.user_id', 'left');
$this->db->where('f.recipe_id', $recipe_id);
$query = $this->db->get()->result();
return $query;
Try this if the above code does not work :
$this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
$this->db->from('feedback f');
$this->db->join('user u','u.user_id = f.user_id', 'left');
$this->db->where('f.recipe_id', $recipe_id);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->row_array();
}

How can I count results from one into a group with different conditions? Linq query

select
count(pat.ID) as PatientEmail,
count(a.ID) as AlaEmails,
count(t.ID) as TrusteeEmails,
count(s.ID) + 1 as SpecialistEmail
from [dbo].[Users] as u
left join [dbo].[Patients] as pat
on u.ID = pat.ID and u.Email != 'email#gmail.com'
left join [dbo].[Patients] as a
on u.ID = a.ID and u.Email = 'email#gmail.com'
left join [dbo].[Trusteehips]as t
on u.ID = t.Trustee_ID
left join [dbo].[Specialists] as s
on u.ID = s.ID and u.Email != 'email#gmail.com'
where u.Active = 1 and u.Deleted = 0
public class UserEmails
{
public int PatientEmail { get; set; }
public int AlaEmails { get; set; }
public int TrusteeEmails { get; set; }
}
public ActionResult ReportByEmail()
{
var res = from u in context.Users
join p in context.Patients
on u.ID equals p.ID into pGroup
join t in context.Trusteeships
on u.ID equals t.Trustee.ID into tGroup
select new UserEmails
{
PatientEmail = pGroup.Count(g => g.Email != "email#gmail.com"),
AlaEmails = pGroup.Count(g => g.Email = "email#gmail.com"),
TrusteeEmails = tGroup.Count()
};
return View(res);
I tried to write this Linq code but it didn't work!
My count result is not shown in one row, I wrote code with same syntax (Group.Count()) and it worked fine, but here it didn't work!

Left Outer Join in Linq to Entities / SQL

How can I write the following SQL in LINQ to Entities?
SELECT r.rolename,
( CASE
WHEN ur.username IS NULL THEN 0
ELSE 1
END ) AS isinrole
FROM bgt.roles r
LEFT OUTER JOIN bgt.usersinroles ur
ON ur.rolename = r.rolename
AND ur.username = 'ADMIN'
This worked for me. Thanks for all the suggestions.
var query =
from r in Roles
from ur in UsersInRoles
.Where(v => v.Rolename == r.Rolename && v.Username == "ADMIN")
.DefaultIfEmpty()
select new { Rolename = r.Rolename, IsInRole = (ur.Username != null) };
The generated SQL is as follows
SELECT
1 AS [C1],
[Extent1].[Rolename] AS [Rolename],
CASE WHEN ([Extent2].[Username] IS NOT NULL) THEN cast(1 as bit) WHEN ([Extent2].[Username] IS NULL) THEN cast(0 as bit) END AS [C2]
FROM [bgt].[Roles] AS [Extent1]
LEFT OUTER JOIN [bgt].[UsersInRoles] AS [Extent2] ON ([Extent2].[Rolename] = [Extent1].[Rolename]) AND ('ADMIN' = [Extent2].[Username])
I would do it like this:
from role in db.Roles
let isInRole = role.UsersInRoles.Any(u => u.UserName == "ADMIN")
select new { role.RoleName, isInRole }
Althought the generated SQL is not as nice as yours.
Extension method for Left join (linq to entities):
public static class DbSetExtensions
{
public static IQueryable<TResult2> LeftJoin<TOuter, TInner, TKey, TResult2>(
this IQueryable<TOuter> outerList,
IEnumerable<TInner> innerList,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<LeftJoinTemp<TOuter, TInner>, TInner, TResult2>> resultSelector2)
{
// (tr, historicPrices) => new { tr, historicPrices }
Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinTemp<TOuter, TInner>>> myResultSelector1
= (tr, historicPrices) => new LeftJoinTemp<TOuter, TInner> { outer = tr, inners = historicPrices };
// e => e.historicPrices.DefaultIfEmpty()
Expression<Func<LeftJoinTemp<TOuter, TInner>, IEnumerable<TInner>>> myCollectionSelector
= e => e.inners.DefaultIfEmpty();
//var a = outerList.GroupJoin(innerList, outerKeySelector, innerKeySelector, resultSelector1);
var a = outerList.GroupJoin(innerList, outerKeySelector, innerKeySelector, myResultSelector1);
//return a.SelectMany(collectionSelector, resultSelector2);
var b = a.SelectMany(myCollectionSelector, resultSelector2);
return b;
}
}
public class LeftJoinTemp<TOuter, TInner>
{
public TOuter outer;
public IEnumerable<TInner> inners;
}
example calling, left join of Transaction and HistoricPrice, for transaction you have to write parent.outer
.LeftJoin(db.HistoricPrices,
transaction => new { transaction.InstrumentId, DateId = transaction.Date2Id },
historicPrice => new { historicPrice.InstrumentId, historicPrice.DateId },
(parent, historicPrice) => new
{
parent.outer.Id,
parent.outer.OpeningDate,
parent.outer.InstrumentName,
historicPrice.DateId,
historicPrice.InstrumentId
})