Linq where statement one to many - c#

Table "aaa" have a column with foreign key to table "bbb" that in turn have it to table "ddd". Table "ddd" have a column with an ID called "costRef"
I want to select those "aaa" that have any of my "ddd" with a specific costRef that my list contains.
var query =
from tr in db.aaa
where tr.bbb.Any(x => x.ccc.ddd.Any(y => intList.Contains(y.costRef)))
select tr;
In that case above I got all of my "aaa" if any have that ref. I can understand that, but it's not what I want :) But How do I manage to do this?
Tried allot with select and where statements instead of my "any". Proberly that's the way to do it but I cant manage it.

I did SQL before Linq was around, so I still tend to follow the same structure. In this case you could just do:
var query = from a in db.aaa
join b in db.bbb on a.FK equals b.ID
join c in db.ccc on b.FK equals c.ID
where intList.Contains(c.costRef)
select a

Related

Select all columns from one table and 1 column from another

I have the following query in linq:
(from creditCard in DbSet
join rank in base.dataContext.ProductVerticalRanks on creditCard.ProductVerticalReferenceId equals rank.ProductVerticalReferenceId
where rank.ClientId == clientId
orderby rank.PreferredOrder
select creditCard)
.Include(creditCard => creditCard.ProductVerticalCompany)
.Include(creditCard => creditCard.Labels);
But now I have a new requirement, I need to add a column 'rank.PreferredOrder' from table 'rank' into the result, is there an easy way of doing this without making a massive 'select' statement, because there are around 20-30 fields in creditCard alone.
I dont have your model in front of me, so can't confirm this or not, but you can use an anonymous object like this:
from creditCard in DbSet
join rank in base.dataContext.ProductVerticalRanks on
creditCard.ProductVerticalReferenceId equals rank.ProductVerticalReferenceId into g
where rank.ClientId == clientId
orderby rank.PreferredOrder
select new {Card = creditCard, Ranks = g}

Nested Select MySQL statements to LINQ

I'm trying to convert the following MySQL statement in to LINQ query format
SELECT * FROM table1 WHERE table1.id IN (SELECT c_id FROM table2 WHERE a_id IN (1, 49) GROUP BY c_id HAVING COUNT(*) = 2) ORDER BY name
Got as far as this, but I'm drawing a blank on how to handle the IN and 2nd SELECT statement
myItems = from c in table1
let id = c.id
where ????
orderby c.name
select c;
Would appreciate some guidance with this please
Try this:
var ids=new[]{1,49};
var innerquery=table2.Where(e=>ids.Contains(e.a_id))
.GroupBy(e=>e.c_id)
.Where(g=>g.Count()==2)
.Select(g=>g.Key);
var myItems = from c in table1
where innerquery.Contains(c.id)
orderby c.name
select c;
First define your inner query,after the group by you will get a collection of IGrouping<TKey, TElement>> that represent a collection of objects that have a common key, filter the groups choosing only those where count==2, and select the keys of those groups. The second part is really easy to understand. I split the process in two queries to do it more readable, but you can merge both query in one.

Convert sql query to lambda expression for table with foreign keys

I have 2 tables. One is a user table that holds userid and userSelection(foreign key to another table) both are primary keys so multiple rows for a user.
The 2nd table holds columns with it's primary id being userSelection.
I want to retrieve all the userSelection rows that a userId has from the 2nd table. I want to use linq lambda expressions too.
I have it working in sql jsut can't convert it for use in c#.
Select * From column
where colID in (
select colId from users
where userID = 'someUser')
Thanks
Assuming you're using Entity Framework, what you're really looking for is an inner join. it would look something like this:
from c in context.Column
join u in context.Users on c.ColId equals u.ColId
where u.UserId = 'SomeUser'
select c;
as a lambda that is something like (syntax might be lacking something) (no where clause here, but easily added)
context.Column.Join( context.Users, u => u.ColId, c => c.ColId).Select
Change this code to two parts
Select * From column
where colID in (
select colId from users
where userID = 'someUser')
First part to get colId list:
var colIds = context.users.Where(x=>x.userID == "someUser").Select(x=>x.colId).ToList();
Second part to get the result use Where and List.Contains
// IQueryable result
var result = context.column.Where(x=>colIds.Contains(x.colID));
You can use it inline, but I recommend it to be two parts.

Select only defined column in LINQ

I am writing a simple LINQ query. Table structure is defined below:
Table A
Id int,
VName varchar2(20),
VAddress varchar2(200)
Table B
Id int,
NName varchar2(20),
NAddress varchar2(200)
LINQ Query
from c in A
join x in B on c.Id equals x.Id
order by A.Id
select New{
c.Id,
x.NName
}
Then SQL Generate as
select Filter1.Id,Filter1.NName from(
Select Extend1.Id,Extend1.VName,Extend1.VAddress,
Extend2.Id as Id1,Extend2.NName,Extend2.NAddress
from A as Extend1 Inner Join B as Extend2 on Extend1.Id=Extend2.ID)
as Filter1
MY Problem: I don't want select many columns in SubQuery.
If you're really worried about performance, then just use plain SQL... it's just about always faster than Linq (in my personal experience). Also, you can try using this Linq to execute your SQL:
IEnumerable<YourDataType> result = DataContext.ExecuteQuery<YourDataType>(SqlString);
You can find out more from the DataContext.ExecuteQuery<TResult> Method (String, Object\[\]) page at MSDN. Please note that this page relates to a different overload of this method, but it has examples in it.

How do I join tables with a condition using LLBLGen?

I have the following Sql Query that returns the type of results that I want:
SELECT b.ID, a.Name, b.Col2, b.COl3
FROM Table1 a
LEFT OUTER JOIN Table2 b on b.Col4 = a.ID AND b.Col5 = 'test'
In essence, I want a number of rows equal to Table1 (a) while having the data from Table2 (b) listed or NULL if the condition, 'test', doesn't exist in Table2.
I'm rather new to LLBLGen and have tried a few things and it isn't working. I can get it to work if the condition exists; however, when a requirements change came in and caused me to rewrite the query to that above, I'm at a loss.
Below is the old LLBLGen C# code that worked for existing products but not for the above query:
LookupTable2Collection table2col = new LookupTable2Collection();
RelationCollection relationships = new RelationCollection();
relationships.Add(LookupTable2Entity.Relations.LookupTable1EntityUsingTable1ID, JoinHint.Left);
IPredicateExpression filter = new PredicateExpression();
filter.Add(new FieldCompareValuePredicate(LookupTable2Fields.Col5, ComparisonOperator.Equal, "test"));
table2col.GetMulti(filter, relationships);
Table 1 has 3 records in it. I need the 3 records back even if all items from Table 2 are NULL because the condition doesn't exist. Any ideas?
You've to add your filter to the relation join like this:
relationships.Add(LookupTable2Entity.Relations.LookupTable1EntityUsingTable1ID, JoinHint.Left).CustomFilter = new FieldCompareValuePredicate(LookupTable2Fields.Col5, ComparisonOperator.Equal, "test");

Categories