Convert SQL query into Linq expression - c#

There are tables Subject, Student and SubjectEnrolled
Subject table have two columns SubjectId and SubjectName
SubjectEnrolled table also have two column StudentID(foreign key to StudentTable) and SubjectId(foreign key to Subject)
I want to convert this SQL query
SELECT SubjectName
FROM Subject
WHERE SubjectId IN
(
SELECT SubjectId
FROM SubjectEnrolled
WHERE StudentID=7
)
Into a Linq or Lamda expression
using (var db = new DbContext())
{
var res = from r in db.Subjects.....
}

1 - SQL : use inner join instead IN :
SELECT SubjectName FROM Subject sub
INNER JOIN SubjectEnrolled subEn on sub.SubjectId = subEn.SubjectId
WHERE subEn.StudentID = 7
2 - Linq Query Join:
var res = (from sub in db.Subjects
join subEn in db.SubjectEnrolleds on sub.SubjectId equals subEn.SubjectId
where subEn.StudentID = 7).ToList();
I hope you find this helpful.

Related

How to write Update logic using LEFT JOIN in LINQ Method Syntax?

In my .Net application, EntityFramework 6 is used and I am writing a logic in C# to update one of the column values of the ORDERTABLE to Yes or No.
In ORDERTABLE, for a Single TranID there will be one or more OrderNumber. I need to update the last OrderNumber (i.e., MAX(OrderNumber)) value of a TranID to 'NO' and for remaining OrderNumber value will be 'YES'.
Below SQL query is giving me the expected result but I am not sure of converting this into LINQ to Entities code logic.
UPDATE SC
SET ORDERVALUE = CASE WHEN SC1.ORDERNUMBER IS NULL THEN 'YES' ELSE 'NO' END
FROM ORDERTABLE SC
LEFT JOIN (SELECT MAX(ORDERNUMBER) ORDERNUMBER, SID FROM ORDERTABLE WHERE STATUS ='A' GROUP BY SID) SC1
ON SC.ORDERNUMBER = SC1.ORDERNUMBER AND SC.SID = SC1.SID
WHERE SC.STATUS ='A' AND SC.SID IN (SELECT ID FROM ORDERMASTER(NOLOCK) WHERE MID = variablename)
Select Query:
SELECT
ORDERVALUE = CASE WHEN SC1.ORDERNUMBER IS NULL THEN 'YES' ELSE 'NO' END,
SC.*
FROM ORDERTABLE SC
LEFT JOIN (SELECT MAX(ORDERNUMBER) ORDERNUMBER, SID FROM ORDERTABLE WHERE STATUS ='A' GROUP BY SID) SC1
ON SC.ORDERNUMBER = SC1.ORDERNUMBER AND SC.SID = SC1.SID
WHERE SC.STATUS ='A' AND SC.SID IN (SELECT ID FROM ORDERMASTER(NOLOCK) WHERE MID = variablename)
In C#, LINQ to Entities code should looks like somewhat similar to below first format (LINQ Method) but not like the second one(LINQ query).
//1. LINQ Method
using (var context = new ProductDBEntities())
{
dbContextTransaction = context.Database.BeginTransaction();
ORDERDETAILS od = context.ORDERDETAILS.Single(G => G.ID == 1);
od.OrderNumber = OrdNumber;
od.LastModifiedBy = createdBy;
od.LastModifiedTS = DateTime.UtcNow;
context.SaveChanges();
}
//2. LINQ Query
using (var context = new ProductDBEntities())
{
var query = from st in context.ORDERTABLE
where ...
select st;
var ORDERTABLE = query.FirstOrDefault<ORDERTABLE >();
}

Error: query body must end with a select clause or a group clause

I'm trying to convert this query from MS-SQL to entity
this is the original query:
SELECT sys_id
FROM table1
inner join table2 on table1.client_id = table2.client_id
and table1.local_seq = table2.local_seq
WHERE table1.client_id = #ClientID
And this is the converted code to Entity
var dbListingSysId = (from type in db.table1
join borrower in db.table2 on new { type.client_id, type.local_seq } equals new { borrower.client_id, borrower.local_seq }
where type.client_id == clientId
select new {type.listingid }).ToList();
But i get error:
A query body must end with a select clause or a group clause

EF (LINQ to SQL) - How to query?

I have the concept of a document that has keyword/s. EF abstracted out the document-keyword joining table to an association.
The structure looks like this
Document: ID (PK)
Document_Keyword: DocumentID (PK), Keyword (PK)
Keyword: Keyword (PK)
I have the requirement to return a list of documents where they contain ALL keywords in a string[]
If I was doing this in SQL it would be similar to below
with t as (
select 'keyword1' KEYWORD union
select 'keyword2'
)
select DocumentID,count(*) from [dbo].[Document_Keyword] p
inner join t on p.KEYWORD = t.KEYWORD
group by DocumentID
having count(*) = (select count(*) from t)
Im struggling to form a linq query that will give me the same result.
I have tried the following LINQ statement however it does returns documents that contain 1 or more of the keywords in the array. I require that documents are only returned if ALL keywords match.
var query = (from k in db.KEYWORD
from b in k.DOCUMENT
join q in arrKeywords //array of string[]
on k.KEYWORD equals q
select new Document()
{
Filename = b.FILENAME,
Description = b.TITLE
});
Any ideas?
Cheers
Jeremy
If I get you well you want entries of which all keywords match exactly, i.e. it doesn't have any other keywords. A way too achieve this is
var kwc = arrKeywords.Count();
var query = from k in db.KEYWORD
let kw = k.DOCUMENT.Select(d => d.KEYWORD)
where kw.All(kw1 => arrKeywords.Contains(kw1))
&& kw.Count() == kwc;
The generated query is still much longer than a hand-coded one would be, but I think the database's query optimizer should be able to handle this.

Convert sql code to linq (Inner join Query)

Could somebody help me please to convert this sql code to linq .
SQL query
select distinct coursecode
from UnitSet_Unit
where UnitCode in ('FDFFSACA' ,'FDFFSCFSAA', 'FDFOPTHCP3A ')
and CourseCode in (Select distinct coursecode
from Trainee_course
where TraineeID =10000088 )
Where UnitCode in IN clause come dynamic and in the form of array .
and the course code in the second part is also have variable count
Off the top of my head, assuming we have the following inputs (and you are working in C#):
var unitCodes = new List<string> { "FDFFSACA" ,"FDFFSCFSAA", "FDFOPTHCP3A" };
var traineeID = 10000088;
This should work:
var result = (from us in db.UnitSet_Unit
where unitCodes.Contains(us.UnitCode)
&& us.CourseCode == (from tc in db.Trainee_course
where tc.TraineeID == traineeID
select tc.CourseCode).Distinct().SingleOrDefault()
select us.CourseCode).Distinct();

Select records count from multiple tables in a single query

I have some models (restaurants, shops, products), and i want to select records count for multiple models in a single linq query.
I know how it should be in sql, but i don't know how to translate it in linq:
select
(select count(*) from restaurants) as restaurantsCount,
(select count(*) from shops) as shopsCount,
(select count(*) from products) as productsCount
from
dual
Considering dual is a dummy table with single row:
var result = new
{
RestaurantsCount = context.Restaurants.Count(),
ShopsCount = context.Shops.Count(),
ProductsCount = context.Products.Count()
};
Single query solution:
var result = from dummyRow in new List<string> { "X" }
join product in context.products on 1 equals 1 into pg
join shop in context.shops on 1 equals 1 into sg
join restaurant in context.restaurants on 1 equals 1 into rg
select new
{
productsCount = pg.Count(),
shopsCount = sg.Count(),
restaurantsCount = rg.Count()
};

Categories

Resources