LEFT LINQ TO SQL C# JOIN on many to many table - c#

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

Related

Right outer join in linq-to-sql

I'm new in LINQ , i have query which i wrote with SQL server and i wanna Translate/convert to LINQ.Can anyone direct me in the right direction? thx
This is my SQL:
SELECT Contact.Name, Contact.E-Mail,
Contact Business Relation.No_
FROM Contact Business Relation RIGHT OUTER JOIN
Contact ON Contact Business Relation.Contact No_ = Contact.Company No_
WHERE (Contact.E-Mail = #mail)
This is my LINQ (I'm not sure i did it in right way):
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact
on cbr.Contact_No_ equals c.Company_No_ into f
from c in f.DefaultIfEmpty()
where c.E_Mail == Mail
select new
{
Mail = c.E_Mail,
No = cbr.No_
};
Unfortunately there are no right joins in linq. However, you can rearrange your query to use a left join instead.
var query = from c in db.Contact
join cbr in db.Contact_Business_Relation
on c.Company_No_ equals cbr.Contact_No_ into f
from cbr in f.DefaultIfEmpty()
where c.E_Mail == Mail
select new
{
Mail = c.E_Mail,
No = cbr.No_
};
Join Clause

.NET SQL Query joining two different tables

I'm brand new to .net MVC, and while I have some basic experience with writing SQL queries, I'm not sure how to go about what I need to do for .NET.
My initial query looks like this:
var results = (from s in db.Members
join sa in db.FocusArea on s.ID equals sa.MemberID
where sa.Area == SearchString
select new { s.ID, s.Name, s.Overview }).ToList();
This is not functioning correctly. It is seaching in the s.Overview for some reason. And, I need to make this query much more complicated. In short, I have three tables I need to search across. And with this query, it is not working:
var conceptResults = (from s in db.Cohorts
join oa in db.OutcomeArea on s.ID equals oa.CohortID
where ((oa.Area.Contains(SearchString))
|| (oa.OutcomeType.Contains(SearchString)))
select new { s.ID, s.Name, s.Overview }).ToList();
I need to use my SearchString to search for matches in both Area and Description in db.FocusArea.
I also need to use my SearchString to search for matches (contains) in another table db.SpecificFocusAreas for column SFocusArea where again the join is the ID/MemberID.
Is there a way to essentially do a join or join type of statement? I don't want to join all three tables because I am looking for results from either of the two joins, not from all joins.

Linq Join variable scoping issue

Really odd issue that I cant work out.
I am trying to join two tables in a linq statement to only retrieve records where the record in table 1 has no related rows in table 2.
I have used Joins before but for some reason I cant get VS to recognise the second table in the linq statement.
EG.
var result =
(from pc in _dataSource.Payments
join bc in _dataSource.BouncedCheques
on pc.PaymentID != bc.PaymentID //This is where the error occurs, VS does not recognise "bc"
where pc.CustomerNumber == getAccountNumber
& pc.IsDeleted == false
orderby pc.PaymentDate descending
select new PaymentAllocation
{
PaymentId = pc.PaymentID,
PaymentDate = pc.PaymentDate,
CustomerNumber = pc.CustomerNumber,
ChequeReference = pc.ChequeReference,
PaymentValue = pc.PaymentValue,
AllocatedValue = pc.AllocatedValue,
UnallocatedValue = pc.PaymentValue - pc.AllocatedValue,
ReceivedBy = pc.ReceivedBy,
PaymentType = pc.PaymentType,
PostedDate = pc.PostedDate
});
Basically the problem is that the variable "bc" does not seem to be recognised, however I have several other similar Linq queries that all work well
Any ideas?
Your problem is that the syntax for join uses the keyword equals and not standard boolean operators.
Try replacing your join by a cartesian product of your tables:
from pc in _dataSource.Payments
from bc in _dataSource.BouncedCheques
where
pc.PaymentID != bc.PaymentID
&& pc.CustomerNumber == getAccountNumber
& pc.IsDeleted == false
In the join clause you should use the equals keyword:
try:
on pc.PaymentID equals bc.PaymentID

Linq to SQL - Group By and Count

I'm trying to convert this query (already working)
SELECT Building.NAME, COUNT([User].ID)
FROM BuildingUser
INNER JOIN Building ON Building.ID = BuildingUser.ID_BUILDING
INNER JOIN [User] ON [User].ID = BuildingUser.ID_USER
GROUP BY Building.NAME
To Linq to SQL, but I don't know what I'm doing wrong. Look at my trying
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users =
};
I just need to group my Buildings and count how many users each one has.
Simply use the the Count method:
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users = grpBuilding.Count()
};

Join two tables in Linq to SQL

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.

Categories

Resources