The concat works, but the outer distinct query does not. The error is 'string does not contain a definition for 'role_name'... Any idea how to make this work?
(from results in ((from pmr in dbContext.project_member_role
join r in dbContext.role on pmr.project_member_role_id equals r.role_id
where pmr.member_id == memberId
select r.role_name)
.Concat(from m in dbContext.member
join r in dbContext.role on m.portal_role_id equals r.role_id
where m.member_id == memberId
select r.role_name))
select results.role_name).Distinct().ToList();
Related
So I have a SQL query that I would like to convert to LINQ.
Here is said query:
SELECT *
FROM DatabaseA.SchemaA.TableA ta
LEFT OUTER JOIN DatabaseA.SchemaA.TableB tb
ON tb.ShipId = ta.ShipId
INNER JOIN DatabaseA.SchemaA.TableC tc
ON tc.PostageId= tb.PostageId
WHERE tc.PostageCode = 'Package'
AND ta.MailId = 'Specification'
The problem I am struggling with is I cannot seem to figure out how to do a left join in LINQ before an inner join, since doing a left join in LINQ is not as clear to me at least.
I have found numerous examples of a LINQ inner join and then a left join, but not left join and then inner join.
If it helps, here is the LINQ query I have been playing around with:
var query = from m in tableA
join s in tableB on m.ShipId equals s.ShipId into queryDetails
from qd in queryDetails.DefaultIfEmpty()
join p in tableC on qd.PostageId equals p.PostageId
where m.MailId == "Specification" && p.PostageCode == "Package"
select m.MailId;
I have tried this a few different ways but I keep getting an "Object reference not set to an instance of an object" error on qd.PostageId.
LINQ is very new to me and I love learning it, so any help on this would be much appreciated. Thanks!
From my SQL conversion recipe:
JOIN conditions that aren't all equality tests with AND must be handled using where clauses outside the join, or with cross product (from ... from ...) and then where
JOIN conditions that are multiple ANDed equality tests between the two tables should be translated into anonymous objects
LEFT JOIN is simulated by using into joinvariable and doing another from from the joinvariable followed by .DefaultIfEmpty().
The order of JOIN clauses doesn't change how you translate them:
var ans = from ta in TableA
join tb in TableB on ta.ShipId equals tb.ShipId into tbj
from tb in tbj.DefaultIfEmpty()
join tc in TableC on tb.PostageId equals tc.PostageId
where tc.PostageCode == "Package" && ta.MailId == "Specification"
select new { ta, tb, tc };
However, because the LEFT JOIN is executed before the INNER JOIN and then the NULL PostageIds in TableB for unmatched rows will never match any row in TableC, it becomes equivalent to an INNER JOIN as well, which translates as:
var ans2 = from ta in tableA
join tb in tableB on ta.ShipId equals tb.ShipId
join tc in tableC on tb.PostageId equals tc.PostageId
where tc.PostageCode == "Package" && ta.MailId == "Specification"
select new { ta, tb, tc };
Use:
var query = from m in tableA
join s in tableB on m.ShipId equals s.ShipId
join p in tableC on s.PostageId equals p.PostageId
where m.MailId == "Specification" && p.PostageCode == "Package"
select m.MailId;
Your query uses a LEFT OUTER JOIN but it doesn't need it.
It will, in practice, function as an INNER JOIN due to your tc.PostageCode = 'Package' clause. If you compare to a column value in a table in a WHERE clause (and there are no OR clauses and you aren't comparing to NULL) then effectively all joins to get to that table will be treated as INNER).
That clause will never be true if TableB is null (which is why you use LEFT OUTER JOIN vs INNER JOIN) - so you should just use an INNER JOIN to make the problem simpler.
How to convert store procedure to linq in nopCommerce c#
My store procedure query
SELECT p.Id
FROM Product p WITH (NOLOCK)
LEFT JOIN Discount_AppliedToProducts dap WITH (NOLOCK)
ON p.Id = dap.Product_Id
LEFT JOIN Product_Category_Mapping pcm WITH (NOLOCK)
ON p.Id = pcm.ProductId
LEFT JOIN Discount_AppliedToCategories dac WITH (NOLOCK)
ON pcm.CategoryId = dac.Category_Id
AND dac.Category_Id IN (1 ,2 ,3 ,4 ,5 ,6)
LEFT JOIN Product_Manufacturer_Mapping pmm WITH (NOLOCK)
ON p.Id = pmm.ProductId
LEFT JOIN Discount_AppliedToManufacturers dam WITH (NOLOCK)
ON pmm.ManufacturerId = dam.Manufacturer_Id
WHERE dap.Discount_Id IN (3)
OR dac.Discount_Id IN (3)
OR dam.Discount_Id IN (3)
My linq query
var productlist = (from q in _productRepository.Table
select q).ToList();
var discount_AppliedToProductIds = (from dp in _discountRepository.Table
from p in dp.AppliedToProducts
select p).ToList().DistinctBy(d => d.Id).ToList();
var discount_AppliedToCategorieIds = (from dp in _discountRepository.Table
from c in dp.AppliedToCategories
select c).ToList().DistinctBy(d => d.Id).ToList();
var discount_AppliedToManufacturerIds = (from dp in _discountRepository.Table
from m in dp.AppliedToManufacturers
select m).ToList().DistinctBy(d => d.Id).ToList();
var product_Manufacturer_Mapping = (from dp in productlist
from pm in dp.ProductManufacturers
select pm).ToList().DistinctBy(d => d.Id).ToList();
var product_Category_Mapping = (from dp in productlist
from pc in dp.ProductCategories
select pc).ToList().DistinctBy(d => d.Id).ToList();
var ss = (from p in productlist
join dap in discount_AppliedToProductIds on p.Id equals dap.Id
join pcm in product_Category_Mapping on p.Id equals pcm.ProductId
//join dac in discount_AppliedToCategorieIds on pcm.CategoryId equals dac.Id
from dac in discount_AppliedToCategorieIds
join pmm in product_Manufacturer_Mapping on p.Id equals pmm.ProductId
join dam in discount_AppliedToManufacturerIds on pmm.ManufacturerId equals dam.Id
from dapd in dap.AppliedDiscounts
from pacd in dac.AppliedDiscounts
from damd in dam.AppliedDiscounts
where discountIds.Any(d => dapd.Id == d || d == pacd.Id || d == damd.Id)
// innner join condition
where categoryIds.Any(d => d == dac.Id) && dac.Id == pcm.CategoryId
select p).ToList();
I have write this code into c# but this code not provide proper result. Now I don't know what is problem into this code. If I run this code into sql server, then I get proper result, but in c# code I don't get proper result.
It's been a long time since I wrote a query in LINQ, but I seem to recall that if you wish to model a LEFT JOIN, you have to use DefaultIfEmpty(), otherwise you end up with an INNER JOIN.
See this, it's answer shows where to apply DefaultIfEmpty:
Linq join iquery, how to use defaultifempty
Obviously if you don't correctly model a LEFT JOIN expression, you'll end up with results only when all 3 inputs produce values.
I would also suggest not using .ToList() on each of your source queries, because that's going to manifest data into memory and use LINQ to Objects for your final query. If you remove the .ToList(), LINQ will construct a single database query for the entire process.
Mark
I have struggling to run linq left on multiple tables.
tableA
Select all the (courseID, code, title) from courseInstances table
tableB
select (studyLevel_ID) from Courses table where courseID from tableA = CourseID from tableB. tableB has courseID
tableC
Select (StudyLevelDescription) from StudyLevel table where studyLevelID from tableB = studyLevel from tableC.
I believe I need left join on table A as I need all the records
I have done separate linq which are working fine but struggling to bring combine result
CourseInstances results
var processedCourseInstance =
(from _courseInstances in _uof.CourseInstances_Repository.GetAll()
join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
into a from b in a.DefaultIfEmpty()
orderby _courseInstances.CourseCode
select _courseInstances).ToList();
StudyLevel results for each course
var _CoursesStudyLevel_Lookup =
(from _course in _uof.Courses_Repository.GetAll()
join _studyLevel in _uof.StudyLevel_Repository.GetAll() on _course.StudyLevelId equals _studyLevel.StudyLevelID
select new {_course.CourseID, _course.StudyLevelId, _studyLevel.LevelDescription }).ToList();
I have managed to combine two results but NOT with LEFT join on CourseInstance table. This time I used LINQPad
from _courseInstances in CourseInstances
join _courses in Courses on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in StudyLevels on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new {_courseInstances.CourseID, _courseInstances.CourseCode, _courseInstances.CourseTitle, _courseInstances.UCASCode, _courses.StudyLevelId, _studylevel.LevelDescription, _studylevel.SLevelType }
for above SQL version as following;
SELECT [t0].[CourseID], [t0].[CourseCode], [t0].[CourseTitle],
[t0].[UCASCode], [t1].[StudyLevelId], [t2].[LevelDescription], [t2].[SLevelType]
FROM [CourseInstances] AS [t0]
INNER JOIN [Courses] AS [t1] ON [t0].[CourseID] = ([t1].[CourseID])
INNER JOIN [StudyLevel] AS [t2] ON [t1].[StudyLevelId] = ([t2].[StudyLevelID])
ORDER BY [t0].[CourseCode]
If i understand correctly, you want something like this?
from _courseInstances in CourseInstances
join c in Courses on _courseInstances.CourseID equals c.CourseID into courses
from _courses in courses.DefaultIfEmpty()
join sl in StudyLevels on _courses.StudyLevelId equals sl.StudyLevelID into studyLevels
from _studylevel in studyLevels.DefaultIfEmtpy()
orderby _courseInstances.CourseCode
select new {
_courseInstances.CourseID,
_courseInstances.CourseCode,
_courseInstances.CourseTitle,
_courseInstances.UCASCode,
_courses.StudyLevelId,
_studylevel.LevelDescription,
_studylevel.SLevelType
}
}
You can create a LINQ left join query with the into keyword and .DefaultIfEmpt().
I have a query that's something like this.
Select a.*
from table1 a
inner join table2 b on a.field1 = b.field1
inner join table3 c on b.field2 = c.field2
where b.field4 = beta and c.field5 = gamma.
On LINQ, I tried to do that this way:
var query = (from a in table1
join b in table2 on a["field1"] equals b["field1"]
join c in table3 on b["field2"] equals c["field2"]
where (b["field4"] == beta && c["field5"] == gamma)
select a).ToList();
But for some reason, when I try to do this I get an error that says that the entity "table2" doesn't have the field Name = "field5", as though as the where clause was all about the last joined table and the other ones were unaccessible. Furthermore, the compiler doesn't seem to notice neither, because it lets me write c["field5"] == gamma with no warning.
Any ideas? Am I writing this wrong?
Thanks
See these links:
How to: Perform Inner Joins (C# Programming Guide)
What is the syntax for an inner join in linq to sql?
Why you don't create View in database, and Select your data from View in LINQ?
For some reason I am getting a "Query body must end with a select clause or a group clause" compile error on what seems to be a simple compound conditional in the following linq-to-sql query:
using (var db = new CaremcDB(Database.Conn))
{
var taxids = from p in db.ProviderTaxIds
join c in db.CustomerProviders
on customerId equals c.CustomerId && p.Id equals c.ProviderId
select p;
return taxids.ToList<ProviderTaxIds>();
}
It chokes on the "&& p.Id equals c.ProviderId" clause for some reason.
It appears that customerId is an external input to the query. Move that to a where clause.
...
on p.Id equals c.ProviderId
where customerId == c.CustomerId
select p;
try this, the parameter names just need to match in the anonymous object
join c in db.CustomerProviders on new { customerId, p.Id } equals new { customerId = c.CustomerId, Id= c.ProviderId }