How to write In query on entity - c#

I have a SQL query which selects top 5000 data with some where conditions. Now my question is how can i write this same query from entity-framework? Is it possible? I wanted know the most effeciant way to achive this query from entity-framework.
Query:
select TOP 5000 * from MyData where Type=1 and UPC not in (
select UPC from MyData where Type=2 AND UPC IS NOT NULL)
C# Entity:
using (var ctx = new db_ProductionEntities())
{
//var items = ctx.MyData.Take(10).ToList(); need to know how to write query here
}

var answer = (from d1 in ctx.MyData
where d1.Type == 1 and
!(from d2 in ctx.MyData
where d2.Type == 2 and d2.UPC != null
select d2.UPC
).Contains(d1.UPC)
order by d1.Id //or some other field, it's needed for "Take"
select d1).Take(5000).ToList();

Related

Convert sql to LINQ query for selection of multiple max columns in c#

SELECT MAX(sectionid) AS SectionId,MAX(displayorder) AS DisplayOrder,propertyid AS PropertyId,1 AS IsSpecSection FROM (
SELECT mp.SectionId ,mp.DisplayOrder ,mp.PropertyId FROM
ModelProperties mp
INNER JOIN PropertySections PS ON mp.SectionId =
ps.SectionId
WHERE ps.IsSpecSection = 1 )s
GROUP BY propertyid
I want to convert above query into LINQ, able to do it for selection of single max column but not for multiple.
I haven't tested the code you have to modify the code as you need
using (var dbContext = new YourEntityName())
{
var result = (from mp in dbContext.ModelProperties
join ps in dbContext.PropertySections on mp.SectionId equals ps.SectionId
where ps.IsSpecSection = 1
group a by new { propertyid } into g
select sectionid , MAX(displayorder)AS DisplayOrder,propertyid AS PropertyId, 1 AS IsSpecSection).ToList();
}
Max value in Linq select Within Innerjoin
You can use this code,
var list=(from mp in ModelProperties
join ps in PropertySections on mp.SectionId equals ps.SectionId
where ps.IsSpecSection == 1
group new { mp, ps } by new { mp.PropertyId } into mgrp
from grp in mgrp.DefaultIfEmpty()
select new
{
grp.mp.SectionId,
grp.mp.PropertyId,
grp.mp.DisplayOrder,
grp.ps.IsSpecSection
}).OrderByDescending(x=>x.SectionId).First();
This query helps you to retrieve ModelProperties rows that has matching SectionId in PropertySections and IsSpecSection has the value 1. Matching rows are then grouped by PropertyId. OrderByDescending sort the retrieved results in descending order of SectionId. First() retrieve the rows that has maximum SectionId for each PropertySections as the rows are sorted in descending order of SectionId.

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 category tree in Entity Framework

I have a Category table with a tree structure (Id,MasterId)
I'd like to select all products that belong to a Category and all Child Categories.
Today I use this SQL Query which works, but I'd like to add pagination and that would be easier with a pure LINQ query. I use Entity Framework 4.
#Count int = 100,
#CategoryId int
with mq as
(
select c.Id as parent, c.Id as child
from dbo.Categories c
where c.Id = #CategoryId
union all
select q.child, c.Id
from mq q
inner join dbo.Categories c on q.child = c.MasterId
)
select top (#Count) P.* from Products P
inner join ProductToCategory PC ON(PC.ProductId = P.Id)
where PC.CategoryId in (
select child from mq
)
and P.PublishStatus = 1
order by P.PublishedDate DESC;
Any ideas how to get a nice LINQ query on this with pagination (current page, number of products per page, total product count)?
This is recursive / hiearchical query with table expression. EF does not provide support for such queries. If you want to receive data by single roundtrip to DB you must wrap it in stored procedure and import that procedure to your entity framework model.
Paging in SQL is also possible when using table expressions and ROW_NUMBER().
there is an idea. i haven't tested it, so dont blame if it doesn't work :P
var ids = context.TreeItems.Where(x => x.Id == parentId).Select(x => (int?)x.Id);
var tmp = ids;
while (true)
{
IQueryable<int?> localIds = tmp;
var subIds = context.TreeItems.Where(x => ids.Contains(x.ParentId)).Select(x => (int?)x.Id);
if (subIds.Any())
{
tmp = subIds;
ids = ids.Union(subIds);
}
else
break;
}
var allSubItems = context.TreeItems.Where(x => ids.Contains(x.Id));

Help with multi table linq query

I have a database set up like so:
Lets say that I have a product group with id of 12. How do I get the CategoryID for this particular Product Group? Would I have to do a join?
Think of it in parts...
How would you do this in SQL?
SELECT DISTINCT sc.CategoryID
FROM SubCategory sc
WHERE sc.SubCategory IN (
SELEcT DISTINCT scpg.SubCategoryID
FROM SubCategoryProductGroups scpg
WHERE scpg.ProductGroupID = 12)
To do this in LINQ2SQL it would be something like this...
using (var db = new MyDataContext()) {
var query = (from sc in db.SubCategories
where (from scpg in db.SubCategoryProductGroups
where scpg.ProductGroupID == 12
select scgp.SubCategoryID).Distinct().Contains(sc.SubCategoryID)
select sc.CategoryID).Distinct();
}
... You could also use joins ...
SQL...
SELECT DISTINCT sc.CategoryID
FROM SubCategory sc
JOIN SubCategoryProductGroups scpg ON sc.SubCategoryID = scpg.SubCategoryID
WHERE scpg.ProductGroupID = 12
LINQ2SQL...
var query = (from sc in db.SubCategories
join scpg in db.SubCategoryProductGroups
on sc.SubCategoryID equals scpg.SubCategoryID
where scpg.ProductGroupID == 12
select sc.CategoryID).Distinct();
... If you LINQ model knows of the relationship you could probably do this ...
var query = (from sc in db.SubCategories
where sc.SubCategoryProductGroups
.Any(s=>s.ProductGroupID == 12)
select sc.CategoryID).Distinct();
dc.subcatogorysproductsgroups.where(o=> o.productgroupid == 12).select(j=> o.subcatogory.catogory);
one thing is if u r using linq to sql then there is no need of using join if the database if fully normilized.
and before using this code ensure the dc.defferedloadingenabled is set to be true.
or use DataLoadOptions and Dc.loadPropery
Hope this helps
var result = from sc in SubCategory
join scpg in SubCategoryProductGroups
on sc.SubCategoryID equals scpg.SubCategoryID
where scpg.ProductsGroupID =12
select sc.CategoryID

Categories

Resources