i would like to have a LINQ statementlike this
in Simple words
i have two tables A and B. A contains fields id,name,amt1,userid. Table B contains id,userid,amt2. I wanted the details of table A in which A.userid=B.userid but B.id!=A.id
Can any one helpmeout. Am a beginner in LINQ
Thanks in advance
Is this what you are trying to do?
TableA.Join(TableB, a => a.userid, b => b.userid, (a, b) => new { A = a, B = b })
.Where(j => j.A.id != j.B.id)
.Select(j => j.A)
Human SQL would be:
select a.*
from tableA a
inner join tableB b on a.userid = b.userid
where a.id != b.id;
Related
Does anybody know how to convert this on outerjoin on LINQ Lambda?
I wan to achieve this using lambda linq
SELECT * FROM Posts as A LEFT JOIN Reactions as B on A.Id = B.PostId AND #userId = b.userid
Here is my current linq code
return await _dbContext.Posts
.GroupJoin(_dbContext.Reactions,
post => post.Id, reaction => reaction.PostId,
(post, reactions) => new { post, reactions })
.SelectMany(x => x.reactions.DefaultIfEmpty(),
(post, reaction) => new { post.post, reaction })
What you want to accomplish can be done in two different ways in SQL, and those ways can be translated to Linq.
Depending on your scenario (volume of data, indexes, etc) you may want to need one or another
Option A: Join the filtered data
SELECT a.Name, b.*
FROM
tableA
LEFT JOIN tableB on
b.Action='delete' AND a.Id = b.Id
would be translated in LINQ to something similar to:
var query =
from a in db.TableA
join pet in db.TableB.Where(x => x.Action=="delete") on a equals b.TableA into gj
from leftJoined in gj.DefaultIfEmpty()
and using method syntax:
var query = tableA
.GroupJoin(
tableB.Where(x => x.Action == "delete"),
tableA => tableA,
tableB => tableB.tableA,
(tableA, tableBs) => new {tableA, tableBs}
).SelectMany(x => x.tableBs.DefaultIfEmpty())
Option B: Do the join and later filter the data
SELECT a.Name, b.*
FROM
tableA
LEFT JOIN tableB on a.Id = b.Id
WHERE
b.Id = NULL OR b.Action='delete'
would be translated to:
var query =
from a in db.TableA
join pet in db.TableB on a equals b.TableA into gj
from leftJoined in gj.DefaultIfEmpty()
where lefjoined == null || leftjoined.Action == "delete"
A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join.
You can use this approach
Query Syntax:
var query = (from post in Posts
join reaction in Reactions
on post.Id equals reaction.PostId
into reaction
from reaction in reaction.DefaultIfEmpty()
select new
{
post.Id,
//prod.Foo1,
//post.Foo2,
//reaction.Foo3,
//reaction.Foo4,
//you can select other fields too
}).OrderBy(ps => ps.Id);
For more information visit Perform left outer joins
Normally you don't. Flattening out related data like that is simply not necessary in LINQ. Just fetch the data with its natural shape:
_dbContext.Posts.Include(p => p.Reactions)
This returns the Posts and any reactions, without having to repeat the Post data for each Reaction, or having nulls for Posts without Reactions.
In SQL I to get the distinct statement, I used join to get it as below
select distinct
col1
from
table1 a
inner join
table2 b on a.code = b.vcode
How can the same be implemented in LINQ over Entity Framework?
Please suggest me.
You can also use method syntax:
var query = table1.Join(table2,
a => a.code,
b => b.vcode,
(a,b) => a.col1)
.Distinct();
var result = (from a in table1
join b in table2 on a.code equals b.vcode
select a.col1).Distinct();
I have two tables and I am joinning them using linq query
TableA with columns ID and Name
TableB with columns ID, TableAID and Order
TableB's column TableAID is a link between TableA and TableB. Please note that TableB my contain rows that do not exist in TableA
My data is as under
TableA
ID Name
1 One
2 Two
3 Three
TableB
ID TableAID Order
1 1 2
2 2 1
3 4 1
4 5 1
In my linq query I want to select all rows from TableB with matching ID in TableA but the list should contain Name from TableA in the order of TableB. So my data should be
Two
One
Please help in building the linq statement
I have tried as below, but dont know where to put the order
var MyList = TableA.Where(x => TableB.Any(y => y.TableAID == x.ID))
.ToList();
Probably your query will be like as given below example,
var data = (from a in context.TableA
from b in context.TableB
where a.ID == b.TableAID
select new
{
a.Name,
b.Order
}).Distinct().OrderByDescending(x => x.Order).ToList();
foreach(var item in data)
{
Console.WriteLine(item.Name);
}
Alternatively, you can rewrite #M. Nasser Javaid answer in:
context.TableA.Join(context.TableB, a => a.ID, b => b.TableAID,
(a, b) => new {a.Name, b.Order}).Distinct()
.OrderByDescending(x => x.Order)
.Select(x => x.Name).ToList()
please try this:
var listresult = (from b1 in TableA
join a1 in TableB on b1.ID equals a1.TableAID
select new
{
b1.Name,
a1.Order
}).ToList().OrderByDescending(x=>x.Order);
var final = (from m in listresult
select m.Name).ToList();
Struggling with converting a normal SQL Query to a LINQ Query that involves multiple LEFT OUTER JOINS..
Original SQL Query:
SELECT a.*
FROM Testers t
LEFT OUTER JOIN Users u ON u.TesterId = t.TesterId
LEFT OUTER JOIN ValidForms v ON v.DepartmentId = u.DepartmentId
LINQ Query Code is as below:
var x = (from t in Context.Testers.AsEnumerable()
from u in Context.Users
.Where(a => a.TesterId == t.TesterId)
.DefaultIfEmpty()
from v in Context.ValidForms
.Where(b => b.DepartmentId == u.DepartmentId)
.DefaultIfEmpty()
Select new myEntity
{
col1 = t.col1,
col2 = t.col2
}).AsEnumerable()
return x.ToList();
Running the query, I am getting an error: Non-static method requires a target
Appreciate if someone could point out how to do the query properly in LINQ.
I also checked the SO question posted here, but I am unable to grasp the concept provided: SQL to Linq query with multiple left outer joins
Thanks.
Update:
I got this from this SO question.
This is a good way to do it. If you follow that example, your code should look something like this:
var x = (from t in Context.Testers.AsEnumerable()
join u in Context.Users on t.TesterId equals u.TesterId into group1
from a in group1.DefaultIfEmpty()
join v in Context.ValidForms on a.DepartmentId equals v.DepartmentId into group2
from b in group2.DefaultIfEmpty()
select new MyEntity {
col1 = b.col1,
col2 = b.col2
}).AsEnumerable();
UPDATED
var x = (from t in Context.Testers.AsEnumerable()
join u in Context.Users on t.TesterId equals u.TesterId
join v in Context.ValidForms on u.DepartmentId equals v.DepartmentId into group1
from b in group1.DefaultIfEmpty()
select new MyEntity {
col1 = (b != null) ? b.col1 : null,
col2 = (b != null) ? b.col2 : null
}).AsEnumerable();
Am new to this here is my T-SQL
SELECT category.id, category.name,COUNT(job.id) AS countofjobs
FROM category
LEFT OUTER JOIN job ON category.id = job.categoryid AND job.active=1
WHERE category.featured=1
GROUP BY category.id, category.name
ORDER BY category.name
what will be the equivalent LINQ to SQL code? any help will be appreciated
Sorry I forgot to mention that there is no relationship database side, tables have no association at all defined in db, thats the main issue, this is really just sample sql to see how I can write Link to SQL for T-SQL that requires: Left outer join, Count of outer join table records and sorting
var result = dataContext.Categories
.Where(c => c.Featured)
.OrderBy(c => c.Name)
.Select(c => new { c.Id,
c.Name,
CountOfJobs = c.Jobs.Count(j => j.Active) };
Alternatively:
var result = from c in dataContext.Categories
where c.Featured
orderby c.Name
select new { c.Id, c.Name, CountOfJobs = c.Jobs.Count(j => j.Active) };
Since you don't have relationships:
var result = from c in dataContext.Categories
where c.Featured
orderby c.Name
select new {
c.Id,
c.Name,
CountOfJobs = dataContext.Jobs.Count(j => j.categoryId == c.Id && j.Active)
};