I've got two tables that I'm trying to join together with an ID, but only select rows from Table A, where a value in Table B is null.
I tried this:
var dbXMLSoccerTeams = (from dbXMLSoccerTeam in data.EFXMLSoccerTeam
where dbXMLSoccerTeam.ID == (from dbMatchTeam in data.EFMatchingTeamIDs
where dbMatchTeam.SmarketsID == null
select dbMatchTeam.XMLSoccerID)
select dbXMLSoccerTeam);
But I get an error saying that operator == can not be used to compare int to iQueryable int
It seems to me that you should actually use a join:
var dbXMLSoccerTeams = from dbXMLSoccerTeam in data.EFXMLSoccerTeam
join dbMatchTeam in data.EFMatchingTeamIDs
on dbXMLSoccerTeam.ID equals dbMatchTeam.XMLSoccerID
where dbMatchTeam.SmarketsID == null
select dbXMLSoccerTeam;
Try:
var dbXMLSoccerTeams = (from dbXMLSoccerTeam in data.EFXMLSoccerTeam
from dbMatchTeam in data.EFMatchingTeamIDs
where dbMatchTeam.SmarketsID == null
&& dbXMLSoccerTeam.ID == dbMatchTeam.XMLSoccerID
select dbXMLSoccerTeam)
Related
How can I perform the following query using Linq
SELECT u.* FROM Users u
INNER JOIN Localities l ON (u.State = l.State or l.State is NULL)
AND (u.City = l.City or l.City is NULL)
You can try out the following query. Also to make it more optimize you can remove your null conditions as inner join will only work if both of the records contains value
var users = from u in Users
join l in Localities on new { A = u.State, B = u.City}
equals new { A = l.State, B = l.City }
select u
l.State is NULL and l.city is null will eliminated by default from inner joins so you don't need to make joins on null
Try the following, you may need to change a bit as it is not tested.
var result = from Users u
join Localities l
on new { u.state, u.City } equals new { l.state, l.City }
where (l.state == NULL || l.City == NULL)
select u;
Am using Linq-to-SQL and have wrote the following query but I need to be able to check that the variable "UserRole.RoleID" is not null.
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
where Member.IsConfirmed || IncludeUnconfirmed && Filter.SelectedMemberRoles.Contains(UserRole.RoleId) // This will sometimes be null
select SystemUser;
I have thought through a number of approaches such as wrapping the query in an if / else statement or creating an anonymous type. Am not sure what the best approach would but I am trying to do something like this:
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
where Member.IsConfirmed || IncludeUnconfirmed
select SystemUser;
if (Filter.SelectedMemberRoles != null)
{
MemberQuery = MemberQuery.Where( // Somthing here
join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
where Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
select /* Somthing */).Any();
}
How can I append the second part of the query wrapped within the if condition to the original query?
You could try this:
var MemberQuery = (from SystemUser
in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID
equals Member.UserId
join _UserRole in Context.webpages_UsersInRoles on Member.UserId
equals _UserRole.UserId into _UserRole
from UserRole in _UserRole.DefaultIfEmpty()
where (Member.IsConfirmed || IncludeUnconfirmed )
&& (
Filter.SelectedMemberRoles == null || UserRole != null
&& Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
)
select SystemUser)
.Distinct();
I have below sql query which I want to convert into LINQ to obtain exactly same results and returned by below query
select *
from (
select distinct DocID
from UserViewDoc
where UserViewDoc.UVID in (102558)) a
left outer join
(
select distinct UserViewDoc.DocID
from UserViewDoc
inner join UserViewHeader on UserViewDoc.UVID = UserViewHeader.UVID
where UserViewDoc.UVID not in (102558)
and UserViewHeader.IsLock = 1) b on a.DocID = b.DocID
where b.DocID is null
)
What I have tried so far is below LINQ statement
var v = (from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
where IDs.Contains(uvd.UVID)
select new { uvd.DocID, uvd.UVID });
var c = ((from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvd.UVID equals uvh.UVID
where !IDs.Contains(uvh.UVID) && uvh.IsLock == true
select new { uvd.DocID, uvd.UVID } ));
var d = (from id in v
join ids in c on id.UVID equals ids.UVID into vc
from sub in vc.DefaultIfEmpty()
where sub == null
select id);
The problem I am facing is running the SQL query is returning 30583 records and LINQ version of it is returning all of the 30613 records
I rewrote the query to be exactly like the sql query, i believe that this is the way:
var firstQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
where IDs.Contains(u.UVID)
select u.DocID).Distinct();
var innerQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvh.UVID equals u.UVID
where IDs.Contains(u.UIVD) == false
&& uvh.IsLock
select u.DocID).Distinct();
var resultQuery = from f in firstQuery
join i in innerQuery on i equals f into lout
from i in lout.DefaultIfEmpty()
where i == null
select f;
i am tying to join multiple columns. There is no problem if column type int or string etc.. but my columns types are smallint.
query:
var getworks = (from loc in db.T_location
join wl in db.T_vehicle_work_list
on new {x=loc.Route_id, y=loc.Cash_center_num}
equals new { x=wl.Route_id, y=wl.Cash_center_num}
where wl.Route_id == getVehicleRouteId.Route_id && wl.Cash_center_num == getVehicleRouteId.Cash_center_num
&& wl.Status_code != "C"
&& wl.Instance_id > bfd
&& wl.Instance_id < afd
select new { loc, wl }).ToList();
error : "The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'."
thanx for help...
If anybody have this problem too. Check the model.edmx column "nullable" properties are same
I need help converting some an SQL select into LINQ
Here is the original SQL:
Select Top 1 IsNull(ct.Template, t.Template) as Template
From Template t
Left Outer Join ClientTemplate ct On t.TemplateTypeId = ct.TemplateTypeId And ct.ClientId = 149
Where t.TemplateTypeId = (Select TemplateTypeId From QuoteType Where QuoteTypeId = 7)
Order By t.Version DESC, ct.Version DESC
I'm using Entity Framework and have entities for QuoteTypes, ClientTemplates and Templates.
The above SQL gets the Template from the ClientTemplate table for client 149 (uses a variable in the real code) for a particular QuoteType. If there is no entry in the CLientTemplate table then it returns the Template from the main Template table for the same QuoteType!
My idea was to query the QuoteType first and then query the ClientTemplate table to see if one exists and if not query the Template table instead. The problem is this will result in three queries but I'm sure it can be done in one swoop!?
Can anyone have a go at writing the LINQ for me?
Here's my mess so far:
QuoteType quoteType = (from qt in this.entities.QuoteTypes where qt.QuoteTypeID == this.SelectedNewQuoteTypeID select qt).First();
if (quoteType != null && quoteType.TemplateTypeID.HasValue)
{
int quoteTypeTemplateTypeID = (int)quoteType.TemplateTypeID;
var query = (from t in this.entities.Templates
join ct in this.entities.ClientTemplates on t.TemplateTypeID equals ct.TemplateTypeID
into a
from b in a.DefaultIfEmpty(new ClientTemplate())
where t.TemplateTypeID == quoteTypeTemplateTypeID
orderby t.Version descending
select new
{
T1 = t.Template1,
T2 = b.Template
}).First();
// Check the query to see if T1 and T2 are null and use whichever one isn't!
// TODO !!!
}
else
{
return string.Empty;
}
I kind of gave up once I got that far and posted this! My example still does two queries and does not select based on the client ID. It also does not have the second order by on the client template table.
I've inherited the original SQL statement so maybe the problem is with that being badly written in the first place!?
Over to you...
I haven't tested it but maybe you could try something like this
from t in this.entities.Template
from ct in this.entities.ClientTemplate.Where(x => t.TemplateTypeId == ct.TemplateTypeId && ct.ClientId == 149).DefaultIfEmpty()
where t.TemplateTypeId == (from x in this.entities.QuoteType where x.QuoteTypeId == 7 select x.TemplateTypeId).FirstOrDefault()
orderby t.Version descending, ct.Version descending
select new { ct.Template == null ? t.Template : ct.Template }
I think this might work, although this is untested, from reading it appears you can't add multiple join conditions to a LinQ statement so you can just specify it in the where clause
So here ya go, I tried to convert the SQL word for word so here's my attempt. If it does everything I think it will do it will work.
int templateTypeId;
templateTypeId= (context.QuoteType.Where(x => x.QuoteTypeId == 7)).FirstOrDefault().TemplateTypeId
var qry =(
from t in context.Template
join ct in context.ClientTemplate on
t.TemplateTypeId equals ct.TemplateTypeId into cts
from ct in cts.DefaultIfEmpty() //left join
where t.TemplateTypeId == templateTypeId
&& ct.ClientId == 149
order by t.Version descending, ct.Version descending
select new
{
Template = (ct.Template != null) ? ct.Template : t.Template //ternary operator
}).FirstOrDefault();