Maybe a quite easy question but I'm new in Linq to SQL. I have two tables
User : UserId,name,Password,Email
USER_TABLE: Id, UserId, FirstName,LastName......
I would like a query that gives for example: userID=3 then give all the details (FirstName,LastName etc)
How can I join these two tables? I would prefer C# code if it is possible!
You do not have to do all the plumbing yourself. If you have the right foreign keys in the database you will not have to join yourself.
You can just do:
var query = from u in db.Users
select new { User = u;
FirstName = u.UserTables.FirstName }
for an inner join use something like:
var query = from u in db.Users
join ut in db.UserTables on u.UserId equals ut.UserId
select new
{
User = u,
Extra = ut
};
It's possible to join tables using linq:
E.g :
var test = (from a in DataContext.User
join b in DataContext.UserTable on a.UserId equals b.UserId
select new
{
UserId = a.UserId,
FirstName = b.FirstName
LastName = b.LastName
}).ToList();
Regards
Like this perhaps:
var joinedResult = from u in context.User
join u2 in context.UserTable on u.UserId equals u2.UserId
select new {
UserId = u.UserId,
FirstName = u2.FirstName
};
I guess your example is just an example, right? Cause it doesn't make much sense splitting that data into two tables.
Related
I have the following query I want to replicate in LINQ:
SELECT A.id,C.quotas, C.fundingid, C.date
,(SELECT value FROM public.fundingsharevalue WHERE fundingid = C.fundingid AND date = C.date) as sharevalue
FROM public.goal A
INNER JOIN public.goaltransactionfunding C ON A.id = C.goalid
where A.userid = 25
Code in LINQ:
var balance = from goal in _context.Goals
join goaltransactionfunding in _context.Goaltransactionfundings on goal.Id equals goaltransactionfunding.Goalid
join user in _context.Users on goal.Userid equals user.Id
where goal.Userid == userid
select new BalanceViewModel
{
FundingId = goaltransactionfunding.Fundingid,
ShareValue = (from fundingsharevalue in _context.Fundingsharevalues
where fundingsharevalue.Id == goaltransactionfunding.Fundingid && fundingsharevalue.Date.Equals(goaltransactionfunding.Date)
select fundingsharevalue.Value).FirstOrDefault(),
Quotas = (double)goaltransactionfunding.Quotas,
Fecha = goaltransactionfunding.Date,
GoalId = goal.Id
};
The problem is with Sharevalue subquery, it doesn't show values when actually it has.
It seems that the query does not fetch anything when it should fetch as it does in SQL.
I'm attaching images for both outputs.
QueryShareValues Image
LINQ sharevalues Image
I am trying to convert the following query in LINQ, tried different links but no luck so far. Please help with below:
SELECT T.TASKID,
T.TITLE,
T.DESCRIPTION,
T.DEADLINE,
T.CREATEDON,
(SELECT EMAIL FROM ASPNETUSERS WHERE ID = T.CREATEDBYUSERID) AS INITIATEDBY
FROM TBL_TASKMEMBERS AS M
INNER JOIN TBL_TASKS AS T ON M.TASKID = T.TASKID
INNER JOIN ASPNETUSERS AS U ON M.USERID = U.ID
WHERE m.UserId = '95d2f49c-0ae6-4571-9d7b-1c498ad0bfac'
Thanks in advance !
Try this:
var result =
from member in TBL_TASKMEMBERS
join task in TBL_TASKS on member.TASKID equals task.TASKID
join user in ASPNETUSERS on user.ID equals member.USERID
join usermail in ASPNETUSERS on usermail.ID equals task.CREATEDBYUSERID
where member.UserId = '95d2f49c-0ae6-4571-9d7b-1c498ad0bfac'
select new { TASKID = task.TASKID, TITLE = task.TITLE, DESCRIPTION = taks.DESCRIPTION, DEADLINE = task.DEADLINE, CREATEDON = task.CREATEDON, INITIATEDBY = usermail.EMAIL };
This is my SQL command
SELECT KEY,NAME
from COMPANY c
WHERE KEY IN (select KEY from USER_COMPANY where UserId = #UserId)
order by NAME asc
So I want to convert it to Entity Framework.
I try like this
var userCompany = (from u in db.USER_COMPANY
where u.UserId == UserId
select(u.KEY));
var user = (from c in db.COMPANY
where (c => userCompany.Contains(c.KEY)
select c);
but it is not working.
How to use the SQL IN keyword in Entity Framework?
Try this:
var query = from c in db.COMPANY
where (from u in db.USER_COMPANY
where u.UserId == UserId
select u.KEY).Contains(c.KEY)
orderby c.NAME
select c.KEY, c.NAME;
Note that this SQL query has the exact same meaning:
SELECT c.KEY, c.NAME
FROM COMPANY c
JOIN (SELECT DISTINCT KEY FROM USER_COMPANY where UserId = #UserId) u
ON U.KEY = C.KEY
ORDER BY c.NAME asc
So you should be able to just do:
var userCompany = (from u in db.USER_COMPANY
where u.UserId == UserId
select(u.KEY)).Distinct();
var result = from c in db.COMPANY
join u in userCompany
on c.KEY = u.KEY
select new {c.KEY, c.NAME};
My understanding is that the translation from .Contains() to IN is only just being added to EF6.
According to this work item (http://entityframework.codeplex.com/workitem/245) and the release note: Improved performance of Enumerable.Contains in LINQ queries.
So look for it in EF6
Hi im kinda new to linq to sql I know about the basics. The problem is I want to do a left join in a query. There are 3 tables in the query.
Claimants ( all rows should be returned from this table)
Claim
User
The query should return all Users who have Claimants. This is done through the many to many table Claim. But regardless of Users all Claimants should be returned. Thus the left join on Claimants.
I have the following query
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
I have tried using an into statement as follows but with no luck
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID
into TheClaimants
from Claims in TheClaimants.DefaultIfEmpty()
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
I would appreciate it if someone could point me in the right direction as to how to use these joins left right correctly and explain how the work. Thank you very much in advance.
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID)
.DefaultIfEmpty()
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
.DefaultIfEmpty()
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
Left outter join
You must know a Luan. If you want all the Claiments to return start by selecting from Claiments and then left join onto the other tables.
Try the following :
LINQ to SQL Left Outer Join
In LINQ, the ".Join()" extension method is the equivalent of SQL inner join.
For outer joins you have to use the ".GroupJoin()" extension method.
Assuming you know the .Join well, the GroupJoin is simple to use. I have to admit that when I first needed to do an outer join in LINQ it was damn hard to find out. I cannot fanthom why did they call it like that.
Although in VB.Net, here's an article that presents various SQL constructs translated into LINQ syntax, even if in VB, still easy to convert to extension methods: http://blogs.msdn.com/b/vbteam/archive/2007/12/31/converting-sql-to-linq-part-6-joins-bill-horst.aspx?Redirected=true
EDIT: #DavidB posted in his comments a much better solution, but only if you can use some ORM navigational properties. If you don't have them, then GroupJoin is probably the most reasonable
I am fairly new to Linq To SQL but trying to run what should be a fairly simple SQL query and can't figure out how to make it play nice in LINQ.
SELECT Users.Id, Users.Id AS Expr1, Users.FirstName, Users.LastName,
User_x_Territory.UserID
FROM Users LEFT OUTER JOIN
User_x_Territory ON User_x_Territory.UserID = Users.Id
GROUP BY Users.Id, Users.Id, Users.FirstName, Users.LastName, User_x_Territory.UserID
HAVING (COUNT(User_x_Territory.UserID) = 0)
Just trying to get all users that do not have a territory assigned, the only way to tell if they have a territory is to check the user_x_territory gerrund.
I am able to get all of the users out of my DB with this:
var users = from u in db.Users
join uXt in db.User_x_Territories on u equals uXt.User into gerr
from users in gerr.DefaultIfEmpty()
select users;
But from there I can't figure out how to add a group by/having to refine the search results to only show users with no territories.
Thanks for any help.
I suggest the following solution.
db.Users.Where(u => u.User_x_Territories.Count == 0)
edit: heh, guess someone beat me to it :(
from t in db.Users
join t0 in db.User_x_Territory on new { UserID = t.Id } equals new { UserID = t0.UserID } into t0_join
from t0 in t0_join.DefaultIfEmpty()
group new {t, t0} by new {
t.Id,
Column1 = t.Id,
t.FirstName,
t.LastName,
t0.UserID
} into g
where g.Count() == 0
select new {
Id = g.Key.Id,
Expr1 = g.Key.Id,
g.Key.FirstName,
g.Key.LastName,
UserID = g.Key.UserID
}
I don't know how efficient this is (I'm guessing not very), but you could try something like this:
var users = (from u in db.Users
join uXt in db.User_x_Territories on u equals uXt.User into gerr
from users in gerr.DefaultIfEmpty()
select u).Where(u => u.User_x_Territories.Count == 0);