inner join query in asp.net MVC4 - c#

I write query about search about specific employee but did'nt work ,I know there is an error in my query but did'nt now where it.
I have 2 tables one for company and another for employee info.
the progress will be:
1'st Query search in company table by department number and company
number then get the PK_companyID .
2'ed JOIN company.PK_companyID==employee.FK_companyID.
3'ed Query will search in employee table by FK_companyID when the
name enter will be the same in employee table.
I hope its Clear to understand
var query = (from c in db.Company
where c.departmentNO== departmentNumber && c.companyNo==companyNumber
join x in db.Employee c.PK_companyID==x.FK_companyID
where (x.FirstName.Contains(firstName ?? x.FirstName)
&& x.SecondName.Contains(secondName ?? x.SecondName)
&& x.ThirdName.Contains(thirdName ?? x.ThirdName)
&& x.FourthName.Contains(fourthName ?? x.FourthName))
select x).ToList();
Thank in advance.

You can simplify your query and your filtering by using code such below, should also result much cleaner SQL if you are not using all your filters.
var employees = (from c in db.Company
join e in db.Employee on c.PK_companyID equals e.FK_companyID
where c.departmentNO == departmentNumber && c.companyNo == companyNumber
select e);
if (!String.IsNullOrEmpty(firstName))
employees = employees.Where(pr => pr.FirstName.Contains(firstName));
if (!String.IsNullOrEmpty(secondName))
employees = employees.Where(pr => pr.SecondName.Contains(secondName));
if (!String.IsNullOrEmpty(thirdName))
employees = employees.Where(pr => pr.ThirdName.Contains(thirdName));
if (!String.IsNullOrEmpty(fourthName))
employees = employees.Where(pr => pr.FourthName.Contains(fourthName));
return employees.ToList();

var query = (from c in db.Company
join x in db.Employee c.PK_companyID == x.FK_companyID
where c.departmentNO == departmentNumber && c.companyNo == companyNumber
&& (x.FirstName.Contains(firstName ?? x.FirstName)
&& x.SecondName.Contains(secondName ?? x.SecondName)
&& x.ThirdName.Contains(thirdName ?? x.ThirdName)
&& x.FourthName.Contains(fourthName ?? x.FourthName))
select x).ToList();

You should use keyword "equals" instead of "==" in join as below:
var query = (from c in db.Company
join x in db.Employee c.PK_companyID equals x.FK_companyID
where c.departmentNO == departmentNumber && c.companyNo == companyNumber
.......
Hope this will work.

Related

How to sort by a specific key and then get the first result in the sorted collection into a group in LINQ

I've got a database where I need to get latest message with (which means a message to OR from me) each user. I'm using LINQ-to-Entities and here is my query:
var latestMessageFromEachUser = from m in Database.Messages.Include(m => m.From).Include(m => m.To)
where !m.IsDeleted && (m.ToID == User.ID || m.FromID == User.ID)
orderby m.ID descending
let otherEnd = m.ToID == userId ? m.FromID : m.ToID
group m by otherEnd into g
orderby g.FirstOrDefault().ID descending
select g.FirstOrDefault();
I think variable names are self explanatory. I'm ordering descending by ID as it's the identity column and is auto-incremented, so it's effectively ordering by date. However, when I execute this query, I'm getting the oldest message with each user instead of newest.
Why?
maybe something like the following:
var test = from m in Database.Messages
where !m.IsDeleted && (m.ToID == User.ID || m .FromID == User.ID)
orderby m.ID descending
let otherEnd = m.ToID == userId ? m.FromID : m.ToID
group m by otherEnd into g
select new { g.Key, g.OrderByDescending(n => n.ID).FirstOrDefault() };
The main issue I see is the sorting on g.FirstOrDefault().ID which got the first of your grouped messages by user and then tried sorting on it which in effect would do nothing
You can do as below
var latestMessageFromEachUser = from m in Database.Messages.Include(m => m.From).Include(m => m.To)
where !m.IsDeleted && (m.ToID == User.ID || m.FromID == User.ID)
let otherEnd = m.ToID == userId ? m.FromID : m.ToID
group m by otherEnd into g
orderby m.ID descending
select g.FirstOrDefault();

Distinct record using linq in entity framework

According to this query i get all records which have same id but i want only one time that record
var query = (from c in CompObj.EmpInfoes
join d in CompObj.Leaves on c.EmpID equals d.ProjectManagerID
where c.RoleID == 4 || c.RoleID == 2
select new { c.EmpName, c.EmpID });
var query = (from c in CompObj.EmpInfoes
join d in CompObj.Leaves on c.EmpID equals d.ProjectManagerID
where c.RoleID == 4 || c.RoleID == 2
select new { c.EmpName, c.EmpID })
.Distinct();
Or was there something more you needed?
Just add .Distinct() at the end.

LINQ syntax and the where clause

I have written some LINQ but it doesn't return the correct data, it seems to ignore my where clause. Can anybody advise me on what I am doing wrong with the syntax?
IEnumerable<Ranking> lst = (from r in results
join m in membersToRank on r.UserId equals m.userId
join t in teamsToRank on m.teamId equals t.teamId
where r.ResultDate >= rankingStart
&& r.ResultDate <= rankingEnd
select new Ranking
{
memberId = m.memberId,
chain = t.chain,
name = m.name,
teamId = m.teamId,
value = results.Count(i => i.IsCorrect && i.UserId == m.userId)
}).ToList();
This line
value = results.Count(i => i.IsCorrect && i.UserId == m.userId)
will bypass the where clause. You have have to repeat the where there
value = results.Where(...).Count(i => i.IsCorrect && i.UserId == m.userId)
or
var results2 = results.Where(...)
and then use only results2.
(as a sidenote, it will even bypass the join, so it could become a little more complex depending on what you want)

How can I write a linq query for this?

I need to write following query in Linq to SQL but not sure what is the best way of doing, given it has two derived tables. Any suggestions.
SELECT A.ID
FROM
(
SELECT *
FROM Orders
WHERE ProductID = 5
) A
JOIN
(
SELECT CustomerID, MAX(Price) Price
FROM Orders
WHERE ProductID = 5
GROUP BY CustomerID
) B
ON A.CustomerID = B.CustomerID and A.Price = B.Price
var b = (
from o in db.Orders
where o.ProductID == 5
group o by o.CustomerID into og
select new {
CustomerID = og.Key
Price = Max(og.Price)
}
);
var a = (
from o in db.Orders
join p in b on new {a.CustomerID, a.Price} equals
new {b.CustomerID, b.Price}
where o.ProductID == 5
select a.ID
);
var r = a.ToString();
These two links are invaluable when forming things like this:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
http://msdn.microsoft.com/en-us/vstudio/bb688085
Can you simplify this with LINQ, especially if you use method syntax instead of query syntax.
orders.Where(o => o.ProductID == 5)
.GroupBy(o => o.CustomerID)
.SelectMany(g => g.Where(o => o.Price == g.Max(m => m.Price)));
My advice when writing LINQ, do not simply attempt to convert a SQL statement exactly. Think about the desired result and develop a solution designed for LINQ.
Something along these lines:
var result = from a in context.Orders
join b in (context.Orders.Where(o => o.ProductID == 5).GroupBy(o => o.CustomerID).Select(g => new { CustomerID = g.Key, Price = g.Max(o => o.Price)))
on new {a.CustomerID, a.Price} equals new {b.CustomerID, b.Price}
where a.ProductID == 5
select a.ID;

Efficient way to sub Queries in Linq

here is my linq code:
BOOK entity = db.BOOKS
.Where(s => s.ID == (from p in db.LIBRARY
from b in db.BOOKS
where (p.ID == 123) && (p.idpage == b.idpage)
select b.fields));
My actual oracle code is:
SELECT DISTINCT BOOKS.ID
FROM LIBRARY,BOOKS
WHERE LIBRARY.ID = 123 AND LIBRARY.ID = BOOKS.ID
But its showing the error in s.ID that..
Delegate 'System.Func Project.Models.BOOKS,int,bool' does not take 1 arguments
Why does this happen? Are there any workarounds?
Your SQL is using a join, so you can do the same thing in LINQ. Either of these approaches will suffice:
// join
var query = (from b in db.BOOKS
join p in db.LIBRARY on b.IdPage equals p.IdPage
where p.ID == 123
select b.Id).Distinct();
// 2 from statements (SelectMany) can also be used as a join
var query = (from b in db.BOOKS
from p in db.LIBRARY
where p.ID == 123 && b.IdPage == p.IdPage
select b.Id).Distinct();
// fluent syntax
var query = db.BOOKS
.Where(b => db.LIBRARY.Any(p =>
p.ID == 123 && b.IdPage == p.IdPage))
.Select(b => b.Id)
.Distinct();
s.ID is comparing to an Enumerable, so you get the error.
At the end of the LINQ query, add a SingleOrDefault().
Your subquery returns a sequence of values, not a single values, so you can't compare it to a scalar property like ID. You should use First on the result of the subquery to get the first result (or Single if there should be only one)
BOOK entity = db.BOOKS
.Where(s => s.ID == (from p in db.LIBRARY
from b in db.BOOKS
where (p.ID == 123) && (p.idpage == b.idpage)
select b.fields).First());
You should be able to use the navigation properties on your BOOKS class to do something like this:
var bookIds = db.BOOKS.Where(b => b.LIBRARIES.Any(l => l.ID == 123))
.Select(b => b.ID)

Categories

Resources