I have 2 queries with LINQ first one is lambda expression and second is only standard LINQ. I want to get the same output in both, but the 2nd query doesn't give me an output.
How I can solve this and what is the logic of joining a table 2 times?
var query1 = _context.UserEdu.Where(x => x.personId == id && x.status ==PersonEducationStatus.SA.ToString())
.Join(_context.Educations.Where(x => x.statusCode == ACTIVE), pe => pe.classNum, s => s.classNum, (pe, class) => class)
.Join(_context.Educations.Where(x => x.isActive), s => s.eduNum, defaultS => defaultS.eduNum, (class, defaultclass) => new
{ class, defaultclass.classNum })
.Join(_context.EducationDocument.Where(...),
s => s.classNum,
rd => rd.entity_id,
(class, rd) => new
{
... output
});
var query2 = (from pedu in _context.UserEdu.Where(x => x.personId == id && x.status == PersonEducationStatus.SA.ToString())
join class in _context.Educations.Where(x => x.statusCode == ACTIVE) on pedu.classNum equals class.classNum
join defaultclass in _context.Educations.Where(x => x.isActive) on pedu.classNum equals defaultclass.classNum
join rd in _context.EducationDocument.Where(...) on defaultclass.classNum equals rd.entity_id
select new
{
... output same with first query
});
Well,
pedu.classNum equals defaultclass.classNum
Is not
s => s.eduNum, defaultS => defaultS.eduNum
IOW, you have used in second join different keys.
Related
Which query is optimized :
db.news.Select(c => new { c.Title, c.Date, c.ID })
.SingleOrDefault(c => c.ID == 1);
or
db.news.Where(c => c.ID == 1)
.Select(c => new { c.Title, c.Date })
.SingleOrDefault();
I want this query:
select title, date
where id = 1
in global which one is better where before select, or where after select?
Generally, Where before Select (Where first approach) is more performant, since it filters your result set first, and then executes Select for filtered values only.
First I have to filter the value based on the Condition value in Table1.
Then I have to join another table called Table2 from Table1. Those two tables have common field Condition2.
At last I should get the value based on the Final condition by joining the Table2 and Table3 common condition (Final_Condition) satisfied values.
I have used below query to get the data. But I got the cross joined result.
var result = db.Table1
.Where(m => m.u.Condition == "Condition")
.Join(db.Table2, u => u.Number, uir => uir.Number, (u, uir) => new { u, uir })
.Where(m => m.u.Condition2 == m.uir.Condition2)
.Join(db.Table3, proposal => proposal.uir.ID.Leasing_Proposal_Id, prop => prop.ID,
(proposal, prop) => new
{
proposal.u,
proposal.uir,
prop
})
.Where(m => m.uir.FinalCondition == m.prop.FinalCondition)
.AsEnumerable()
.Select(m => new Model
{
Name = m.Name,
Id = m.Id,
Dept = m.Dept
})
.Where(m => ((m.Name != null) ? m.Name.ToUpper().Contains("xxx") : false))
.Cast<IResult>()
.ToList();
How do fetch data from multiple tables with method syntax without using joins, but only .where() methods?
I'm making a select against EF5 db context which maps to this legacy table structure where I have a persons detail table and another table which refers both to itself to create a hierarchy and to the person details table this way:
PersonSet
.Where(p => p.LastName.ToLower()=="surname")
.Join(SubsetSet, p => p.Id, ss => ss.SubsetLink, (p, ss) => new { PersonDetail = p, person = ss })
.Where(m => m.person.Frame=="a" && m.person.Purpose=="1")
.Join(SubsetSet, ss1 => ss1.person.Owner, person => person.SubsetLink, (ss1, ss2) => new { person = ss1, club = ss2 })
.Where(a => a.club.Frame=="b" && a.club.Purpose=="2")
.Join(SubsetSet, ss => ss.club.Owner, ss2 => ss2.SubsetLink, (ss, ss2) => new { club = ss, association = ss2 })
.Where(a => a.association.Frame=="b" && a.association.Purpose=="3")
.Join(SubsetSet, ss => ss.association.Owner, ss3 => ss3.SubsetLink, (ss, ss3) => new { association = ss, district = ss3})
.Where(d => d.district.Frame=="b" && d.district.Purpose=="4" && d.district.SubsetLink=="12345")
.Select(proj => new { proj.association.club.person, proj.association.club, proj.association, proj.district })
.OrderByDescending(a => a.association.club.person.phyperson.FirstName)
.Take(10).Dump();
The above query works at least in LinqPad but, it seems to me that If I could get rid of those joins the statement might look a bit nicer. Now I know, like in the Albahari example below, that this can be done with query syntax. But I couldn't find an example that would illustrate this situation with method syntax. The way I'm trying to approach this might of course be wrong and that's why I can't find suitable examples.
Here I found something similar, but couldn't make it work in LinQPad:
Is multiple .Where() statements in LINQ a performance issue?
Or this one, where the solution is again in query syntax:
Cross Join with Where clause
Or this example by Albahari: (http://www.linqpad.net/WhyLINQBeatsSQL.aspx)
from p in db.Purchases
where p.Customer.Address.State == "WA" || p.Customer == null
where p.PurchaseItems.Sum (pi => pi.SaleAmount) > 1000
select p
Consider this query:
var q = from order in orders
from orderline in order.Lines
where orderline.Count > 10
select order.Discount * orderline.Price;
this more or less corresponds to
var q = orders
.SelectMany(order => order.Lines, (order, orderline) => new { order, orderline})
.Where(item => item.orderline.Count > 10)
.Select(item => item.order.Discount * item.orderline.Price);
For more information on SelectMany, see the MSDN documentation.
If you don't have associations defined:
var q = from order in orders
from orderline in orderLines
where orderline.OrderId == order.Id
where orderline.Count > 10
select order.Discount * orderline.Price;
this more or less corresponds to
var q = orders
.SelectMany(order => orderLines, (order, orderline) => new { order, orderline})
.Where(item => item.orderline.OrderId == item.order.Id)
.Where(item => item.orderline.Count > 10)
.Select(item => item.order.Discount * item.orderline.Price);
I'm trying to translate a linq query using query keywords to the method syntax.
My ultimate goal is to be able to apply additonnal restrictions at runtime each time you see a Where clause in the query. I have a total of 14 different parameters to be applied. Some are mutually exclusive, other are inclusive.
Here is the starting query :
query = from p in context.Person
where p.Firstname.ToUpper().StartsWith(firstName.ToUpper())
join v in context.Visit on p.Id equals v.PersonId
where !v.AccessionNumber.StartsWith(RISConst.PM_PREFIX)
join f in context.Finding on v.Id equals f.VisitId
join c in context.Consultation on f.Id equals c.FindingId
where c.StudyId.ToUpper().CompareTo(studyId.ToUpper()) == 0
select v;
Using Jon Skeet's excellent blog post I have been able to go that far :
query = context.Person.Where(p => p.Firstname.ToUpper().StartsWith(firstName.ToUpper()))
.Join(context.Visit, p => p.Id, v => v.Id, (p, v) => new { p, v })
.Where(z => z.v.AccessionNumber.StartsWith(RISConst.PM_PREFIX))
.Select(z => z.v)
.Join(context.Finding, v => v.Id, f => f.VisitId, (v, f) => new { v, f })
.Select(t => t.f)
.Join(context.Consultation, f => f.Id, c => c.FindingId, (f, c) => new { f, c })
.Where( u => u.c.StudyId.ToUpper().CompareTo(studyId.ToUpper()) == 0)
.Select(????);
Now I'm stuck because I need to return Visits. How can I do that ?
Any Help appreciated.
I think you lost Visists on this select statement: .Select(t => t.f). Remove it and work with whole anonymous object on next statement.
.Join(context.Consultation, x => x.f.Id, c => c.FindingId, (x, c) => new { x.v, c })
.Where( u => u.c.StudyId.ToUpper().CompareTo(studyId.ToUpper()) == 0)
.Select(u => u.v);
I'm have a SQL statement which I am trying to transform in a LINQ statement...
SELECT DISTINCT mc.*
FROM ManufractorCategories mc
WHERE mc.Active = 'true'
AND mc.Folder = 'false'
AND (mc.Id not in (SELECT Category_id FROM Manufractor_Category
WHERE Manufractor_id = 3));
That's my last, not working LINQ statement
(IQueryable<object>)db.ManufractorCategories
.Where(o => o.Active == active)
.Where(o => o.Folder == folder)
.Select(i => new { i.Id, i.Folder }).Except(db.Manufractor_Categories.Where(t => t.Manufractor_id == id).Select(t => new { t.Category_id })).Distinct();
I've tried the whole Sunday on that, but the Except statement won't work.
Thanks in advances for any help!
The Except method requires two sets of the same type - this means that you would have to select objects of type ManufractorCategory in the nested query as well as in the outer query - then it would select all categories that are in the first one and not in the second one.
An easier alternative is to use the Contains method to check whether the current ID is in a list of IDs that you want to filter. The following should work:
var q =
db.ManufractorCategories
.Where(o => o.Active == active)
.Where(o => o.Folder == folder)
.Select(i => new { i.Id, i.Folder })
.Where(o =>
!db.Manufractor_Categories
.Select(t => t.Manufractor_id)
.Contains(o.Id)
.Distinct();
And a simplified version using query syntax:
var q =
from o in db.ManufractorCategories
where o.Active == active && o.Folder == folder &&
db.Manufractor_Categories
.Select(t => t.Manufractor_id)
.Contains(o.Id)
select new { i.Id, i.Folder };
The Except statement is going to get a list of objects with the Category_id property. However, you're query has a result that contains objects with the Id and Folder properties. The query will most likely be unable to see where these objects are equal, and so, the Except clause won't take effect.