Entity Framework many to many retrieval data with LINQ - sql

I have two tables AspNetUsers and AspNetRoles with many to many dependence in table AspNetUserRoles. I want to display any user with his role ( if role is null i want to display that ).
In SQL query is:
SELECT u.Email, u.FirstName, u.LastName, r.Name as 'Role'
FROM AspNetUserRoles as ur
RIGHT JOIN AspNetUsers as u
ON ur.UserId = u.Id
LEFT JOIN AspNetRoles as r
ON ur.RoleId = r.Id
I want to transform it into LINQ query. I write query for my AspNetUserRoles table and retriev data, but result display only if have user with role.
IQueryable<RoleViewModel> result = from user in context.AspNetUsers
from r in user.AspNetRoles
select new RoleViewModel{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r.Name
};
Can you help me?
EDIT
That is work:
IQueryable<RoleViewModel> result = from user in context.AspNetUsers
from r in user.AspNetRoles.DefaultIfEmpty()
select new RoleViewModel{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r != null ? r.Name : null
};

Use DefaultIfEmtpy method to join with linq:
var result = from user in context.UserEntities
from r in user.RoleEntities.DefaultIfEmpty()
select new
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Role = r != null ? r.RoleName : null
};

Related

Two queries return different data

I am running two queries according to me both should return same result, but i think i am missing something
SELECT "id", "email", "first_name", "last_name", locale
FROM "users" AS "users"
WHERE (
EXISTS (
SELECT cf.field_value, ucf.field_value
FROM custom_fields cf
LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
WHERE cf."id" = 272 AND
((
cf.field_value = 'true') OR
(
ucf.user_id = users.id AND ucf.field_value = 'true'))
))
it returns record
SELECT users.id, cf.field_value, ucf.field_value, ucf.user_id
FROM users
Join custom_fields cf on cf.user_id = users.id
LEFT join users_custom_fields ucf on ucf.custom_field_id = cf."id"
WHERE cf."id" = 272 AND
((
cf.field_value = 'true') OR
(ucf.user_id = users.id AND ucf.field_value = 'true'))
and it doesn't return anything, is there any difference between these two?
your second query you also join custom_fields table with cf.user_id = users.id. first query does not have this.
With adding cf.user_id = users.id, your first query equal the second.
SELECT "id", "email", "first_name", "last_name", locale FROM "users" AS "users" WHERE (
EXISTS (
SELECT cf.field_value, ucf.field_value
FROM custom_fields cf
LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
WHERE cf."id" = 272
AND cf.user_id = users.id
AND (( cf.field_value = 'true') OR
( ucf.user_id = users.id AND ucf.field_value = 'true'))
))

LEFT join AND command in yii2

I want to write a query in yii2
and i dont know how to write it
i tried few things from documentaion but its not working
here is my query
SELECT notification.*,event.title,user.firstname,user.lastname FROM notification
LEFT JOIN event ON event.id = notification.source_id
AND notification.activity_type = "checkin"
Where user.firstname in (select id from user where user_id=1)
LEFT JOIN user ON user.id = notification.source_id
AND notification.activity_type = "friend"
Where user.firstname in (select id from user where user_id=1)
and here is the query i write for now,i need to add AND function just like its in the query
$query ->select(['notification.*,event.title,user.firstname,user.lastname'])
->from('notification')
->leftJoin('event', 'event.id = notification.source_id')
->leftJoin('user', 'user.id = notification.source_id');
Have you tried the following:
$query ->select(['notification.*,event.title,user.firstname,user.lastname'])
->from('notification')
->leftJoin('event', 'event.id = notification.source_id AND notification.activity_type = "checkin" ')
->leftJoin('user', 'user.id = notification.source_id AND notification.activity_type = "friend"');

Convert SQL query with inner, left, and nested select to LINQ

how can convert this query to linq?
SELECT p.PostID, p.PostText, p.PublishDate, u.Name
FROM AspNetUsers u INNER JOIN Posts p ON u.Id = p.PostUserID LEFT JOIN Reposts r ON p.PostID = r.PostID
WHERE p.PostUserID = 'id'
OR p.PostUserID IN ( SELECT FollowingUserID FROM Friends WHERE FollowerUserID = 'id' AND isUnfollow = 0)
OR p.PostID in (SELECT PostID FROM Reposts WHERE RepostUserID = 'id' OR RepostUserID IN ( SELECT FollowingUserID FROM Friends WHERE FollowerUserID = 'id' AND isUnfollow = 0))
ORDER BY p.PostUserID
Does this work?
var results = from u in AspNetUsers
join p in Posts on u.Id equals p.PostUserID
join r in Reposts on p.PostId equals r.PostId into records
from record in records.DefaultIfEmpty()
where p.PostUserID == "id"
|| (from friend in Friends
where friend.FollowerUserID == "id"
&& friend.isUnfollow == 0
select friend.FollowingUserID
).Contains(p.PostUserID)
|| (from r2 in Reposts
where r2.RepostUserID == "id"
|| (from friend2 in Friends
where friend2.FollowerUserID == "id"
&& friend2.isUnfollow == 0
select friend2.FollowingUserID
).Contains(r2.RepostUserID)
select r2.PostID
).Contains(p.PostID)
orderby p.PostUserID ascending
select p.PostID, p.PostText, p.PublishDate, u.Name;

Converting SQL to LINQ to Entity

I am trying to convert the following SQL, not written by myself, into a Linq to Entity query.
select
u.user_Id,
u.forename,
u.surname,
u.client_code,
u.user_name,
u.password,
u.email,
u.gender,
u.Report_Date,
u.EmailDate,
count(ut.test_Id) as testcount,
sum(cast(isnull(ut.completed,0) as int)) as Testcompleted,
u.job_function,
lu.lookupvalue
from
users u inner join user_Relationship ur
on u.user_Id= ur.child_Id
left join user_tests ut
on ut.user_id=u.user_id
inner join lookup lu on u.first_languageId = lu.lookupid
where ur.parent_Id = #Parent_Id
group by
u.user_Id, u.forename,u.surname,u.client_code,u.user_name, u.password,
u.email, u.gender, u.first_languageId, u.Report_Date,u.EmailDate,
u.job_function, lu.lookupvalue
So far, I have been able to do this:
from u in db.Users
join ur in db.User_Relationship on u.User_ID equals ur.Child_ID
join ut in db.User_Tests on u.User_ID equals ut.User_ID into ps
from ut in ps.DefaultIfEmpty()
join lu in db.Lookups on u.First_LanguageID equals lu.LookupID
where ur.Parent_ID == 45875
select new UserViewModel
{
User_ID = u.User_ID,
Forename = u.Forename,
Surname = u.Surname,
Client_Code = u.Client_Code,
User_Name = u.User_Name,
Password = u.Password,
Email = u.Email,
Gender = u.Gender,
Report_Date = u.Report_date,
Email_Date = u.EmailDate,
//Insert Test_Count and Test_Completed
Job_Function = u.Job_Function,
Lookup_Value = lu.LookupValue
});
How do I replicate the Group and Count() function of SQL?
Well tweak around this solution coz currently i dont have .Net environment for testing this solution, but you'll sure get how grouping is done in linq.
from u in db.Users
join ur in db.User_Relationship on u.User_ID equals ur.Child_ID
join ut in db.User_Tests on u.User_ID equals ut.User_ID into ps
from ut in ps.DefaultIfEmpty()
join lu in db.Lookups on u.First_LanguageID equals lu.LookupID
where ur.Parent_ID == 45875 group new{u,lu} by new {u.User_ID,u.Forename,
u.Surname,u.Client_Code,
u.User_Name,u.Password,
u.Email,u.Gender,u.Report_date,
u.EmailDate,u.Job_Function,
lu.LookupValue} into g
let Test_Count = ps.Count(x=>x.test_Id)
let Test_Completed = ps.Sum(x=>x.completed)
select new UserViewModel
{
User_ID = g.Key.User_ID,
Forename = g.Key.Forename,
Surname = g.Key.Surname,
Client_Code = g.Key.Client_Code,
User_Name = g.Key.User_Name,
Password = g.Key.Password,
Email = g.Key.Email,
Gender = g.Key.Gender,
Report_Date = g.Key.Report_date,
Email_Date = g.Key.EmailDate,
Test_Count = Test_Count,
Test_Completed = Test_Completed,
Job_Function = u.Job_Function,
Lookup_Value = lu.LookupValue
});

SQL query with multiple Joins using CodeIgniter active records

I have this working query:
$q = $this->db->query('SELECT u.name FROM users u
JOIN user_group ug ON u.id = ug.user_id
JOIN groups g ON g.id = ug.group_id WHERE ug.group_id = "4" ');
And I want to replace it with aactive record. I come up with something like this but obviously it doesn't work :
$this->db->select('name');
$this->db->from('users');
$this->db->join('user_group', 'user_group.user_id = users.id);
$this->db->join('groups', 'groups.id = user_group.group_id');
$q = $this->db->get();
Thanks
Leron
I think you forget add where clause. And there was single quote missing.
$this->db->select('name');
$this->db->from('users');
$this->db->join('user_group', 'user_group.user_id = users.id');
$this->db->join('groups', 'groups.id = user_group.group_id');
$this->db->where('user_group.group_id', 4);
$q = $this->db->get();