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();
Related
I am trying replicate the SQL below using LINQ and Entity Framework and cannot figure out how this should be written.
My simplistic LINQ version does a query per table
public IActionResult Index()
{
dynamic view = new ExpandoObject();
view.AppUsers = Context.AppUsers.Count();
view.CustomerShops = Context.CustomerShops.Count();
view.FavouriteOrders = Context.FavouriteOrders.Count();
view.Items = Context.Items.Count();
view.ItemVariations = Context.ItemVariations.Count();
view.MenuCategories = Context.MenuCategories.Count();
view.MenuCategoryProducts = Context.MenuCategoryProducts.Count();
view.Orders = Context.Orders.Count();
view.Products = Context.Products.Count();
view.ProductVariations = Context.ProductVariations.Count();
view.Shops = Context.Shops.Count();
view.Staffs = Context.Staffs.Count();
return View(view);
}
I use this pattern from time to time to for reporting on my column counts and thought this should be easy to do in LINQ, but no luck so far.
This pure SQL UNION would only generate 1 SQL request, instead of a request per table.
select * from (
select 'asp_net_roles' as type, count(*) from asp_net_roles
union
select 'asp_net_user_roles' as type, count(*) from asp_net_user_roles
union
select 'asp_net_users' as type, count(*) from asp_net_users
union
select 'app_users' as type, count(*) from app_users
union
select 'shops' as type, count(*) from shops
union
select 'staffs' as type, count(*) from shops
union
select 'items' as type, count(*) from items
union
select 'item_variations' as type, count(*) from item_variations
union
select 'products' as type, count(*) from products
union
select 'product_variations' as type, count(*) from product_variations
union
select 'menu_categories' as type, count(*) from menu_categories
) as counters
order by 1;
I saw a partial implementation [linq-group-by-multiple-tables] (https://stackoverflow.com/a/3435503/473923) but this is based of grouping data.
FYI: I'm new to C#/Linq, so sorry if this seams obvious.
Use the this code from my answer
And fill ExpandoObject with result:
var tablesinfo = Context.GetTablesInfo();
var expando = new ExpandoObject();
if (tablesinfo != null)
{
var dic = (IDictionary<string, object>)expando;
foreach(var info in tablesinfo)
{
dic.Add(info.TableName, info.RecordCount);
}
}
Idea is that you can UNION counts if you group entities by constant.
Schematically function builds the following IQueryable Expression:
var tablesinfo =
Context.AppUsers.GroupBy(x => 1).Select(g => new TableInfo{ TableName = "asp_net_roles", RecordCount = g.Count() })
.Concat(Context.MenuCategories.GroupBy(x => 1).Select(g => new TableInfo{ TableName = "menu_categories", RecordCount = g.Count() }))
.Concat(Context.Items.GroupBy(x => 1).Select(g => new TableInfo{ TableName = "items", RecordCount = g.Count() }))
....
There is nothing wrong with your LINQ query. It's very acceptable approach. However it's not the most efficient.
There is no need to fetch count from individual tables one by one. You can get the counts from all the tables at once using the System tables Sys.Objects and Sys.Partitions. Just try running this query in your database.
SELECT A.Name AS TableName, SUM(B.rows) AS RecordCount
FROM sys.objects A INNER JOIN sys.partitions B
ON A.object_id = B.object_id
WHERE A.type = 'U' AND B.index_id IN (0, 1)
GROUP BY A.Name
For quick response and cleaner code, you can store this SQL query in a string variable, and run the LINQ
var result = dataContext.ExecuteQuery<YOUR_MODEL_CLASS>
(your_string_query);
I would put something like this:
Dictionary<string, int> view = new() {
new() {'asp_net_roles', Context.AppUsers.Count() },
...
}
return View(view);
maybe not the most pure way, but does the job (unless I misunderstood what you try to accomplish)
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.
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();
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.
Here is my sql query as follow
select enq_Id,enq_FromName,
enq_EmailId,
enq_Phone,
enq_Subject,
enq_Message,
enq_EnquiryBy,
enq_Mode,
enq_Date,
ProductId,
(select top 1 image_name
from tblProductImage as i
where i.product_id=p.product_Id) as imageName,
p.product_Name,
p.product_code
from tblEnquiry as e
inner join tblProduct as p ON e.ProductId=p.product_Id
where ProductId is not null
And I try to convert this sql statement into linq as follow
var result = from e in db.tblEnquiries
join d in db.tblProducts
on e.ProductId equals d.product_Id
where e.ProductId != null
orderby e.enq_Date descending
select new {
e.enq_Id,
e.enq_FromName,
e.enq_EmailId,
e.enq_Phone,
e.enq_Subject,
e.enq_Message,
e.enq_EnquiryBy,
e.enq_Mode,
e.enq_Date,
d.product_Id,
d.product_Name,
imageName = (from soh in db.tblProductImages
where soh.product_id == e.ProductId
select new { soh.image_name }).Take(1)
};
But problem its giving me imageName in a nested list but i want that imageName just as a string .
I also check by using quick watch and in following image you can see that imageName appearing in inner list .
Instead of Take(1) which returns sequence IEnumerable<string>, use FirstOrDefault() which returns single string value (or null if there is no results). Also don't create anonymous type for subquery result:
imageName = (from soh in db.tblProductImages
where soh.product_id == e.ProductId
select soh.image_name).FirstOrDefault()
BTW FirstOrDefault() generates TOP(1) SQL.