I am new to LINQ and don't know how to write group by query. I have one table with three columns contact_id, order_id, product_id and I have two sql queries
Select Top 10 Count(order_id) 'No. Of Orders', order_id, contact_id from SampleData
Group by order_id, contact_id
Order by 1 Desc
--===========================================================================
--Most Popular products
--===========================================================================
Select Count(order_id) 'Most Popular products', product_id from SampleData
Group by product_id
Order by 1 Desc
How to write LINQ query for the same.
Thanks in Advance.
Take a look to this liker using that tool you can compare your sql statements and translate them into linq, that's a nice aid while you're learning linq, it's not going to help you only with groups by but to understand in a practical way how to use linq to sql.
this answer is a good reference to solve your query
Related
Am a front-end dev. Let's get that out of the way... My issue is I need to get some data out of a few tables within the DB. The backend is written in C#. (I will try to answer questions on it if need be) which is not my area.
My SQL is just about average, I can understand enough to write the query that I need see below:
(I've sanitized the table names)
SELECT *
FROM (SELECT * FROM table_1 UNION SELECT * FROM table_2) name
JOIN (SELECT OrderNo, ID FROM table_3 UNION SELECT OrderNo, ID from table_4) name_2
ON name.OrderNo = name_2.OrderNo
WHERE name_2 = <queryParam>
The difficult part is that I need to be able to run this query by varying search terms, by order number, by telephone number and by branch ID using linq.
Can anyone help and also point me in the direction of (preferably easy) resources to learn?
I have:
Simple search engine which is a dynamically built sql query. From this query I'm receiving product Id and Points (search rank). This query is based on search configuration. User can chose which fields he want to search and etc.
IQueryable where are my products with filters applied and some additional data joined.
What I want to do:
Join results from Sql Query with IQueryable so I will have my products that fulfill search conditions and other filters and have Points joined. I need to get my results as IQuryable
I have tried to rewrite this search engine to linq but I ended up with really huge and slow queries.
I've tried to fire up my sql query and get it as IQueryable and then join it to my IQueryable. That didn't worked out got some error.
Any tips?
EDIT:
Sample SQL Search Query;
SELECT Id, SUM(Points) AS Points
FROM (
SELECT tw_Id Id ,500 AS Points
from tw__Towar
Where
tw_Nazwa Like '%WA20-800%'
union all
SELECT tw_Id Id ,2500 AS Points
from tw__Towar
Where
tw_Nazwa Like '%WA20-800%'
union all
SELECT tw_Id Id ,5000 AS Points
from tw__Towar
Where
tw_Symbol Like 'WA20-800 %') sub
group by Id
The code gets way more complicated when there are more then one keyword.
I've tried to execute it in way:
dbcontext.Database.SqlQuery<PointsId>(query).AsQueryable();
and then join it to my IQueryable. But it didn't worked.
I would like to know how to efficiently count (SQL server side) the amount of distinct count of results for a specific range of a related entity that has a many to many relationship.
This is the current situation in entity Framework:
Table1 1<------->∞ Table2
Table2 ∞<------->∞ Table4
Table 2 and Table 4 have a many to many relationship and are linked with Table3 in SQL.
What I want is the distinct count of table4 results related to a specific range of Table1.
In LinQ to SQL the query is this:
(from dc in Table1
join vc in Table2 on dc.Table1Id equals vc.Table2Id
join vcac in Table3 on vc.Table2Id equals vcac.Table3Id
join ac in Table4 on vcac.Table3Id equals ac.Table4Id
where dc.Table1Id > 200000
group ac by ac.Table4Id into nieuw
select new { acid= nieuw.Key}).Count()
This lets SQL server return the count directly.
Because the extra table for the many to many relation ( Table3) is gone, I have had problems converting this query to L2E in query syntax. ( since I cannot join table 4 with table 2 with an inner join).
I have this in chained syntax, however, is this efficient ( does this fetch the whole list, or does it let SQLserver do the count, as I'm not sure this is an efficient way to select, Table 2 contains about 30.000 entries, I don't want it to fetch this result just to count it):
context.Table4.Where(a => a.Table2.Any(v => v.Table1Id > 200000)).Select(a => aTable4Id).Distinct().Count();
How would I go converting the Linq2SQL query into L2E in the query syntax ? Or is the chained syntax fine in this situation ?
The .Select() method uses deferred execution, meaning it won't actually run the query until you need the results. At that point in the chain it still exists only as a query definition. Then you modify with .Distinct() before getting .Count() - which does query the database using a SQL GROUP BY statement. So you should be good.
I have no experience with the .NET Entity Framework and I have some doubts about what exactly do this query:
using (MyCorpo.EarlyWarnings.Model.EarlyWarningsEntities context = new Model.EarlyWarningsEntities())
{
DBContext.SetTimeout(context);
model.VulnerabilitySeverityAverage = (from x in context.VulnerabilityAlertDocuments select x.Severity).Average();
}
(Where the type of the model.VulnerabilitySeverityAverage is simply a string)
So I think that VulnerabilityAlertDocuments map the VulnerabilityAlertDocument database table because into the EarlyWarningsEntities I have something this line:
public DbSet<VulnerabilityAlertDocument> VulnerabilityAlertDocuments { get; set; }
So I am executing a query on the VulnerabilityAlertDocuments DbSet object that represent a query on my VulnerabilityAlertDocument table on my database. Is it correct?
So what exatly do the previous query?
I think that it select the Severity field value of all records in the VulnerabilityAlertDocument table and calculate the avarage value from all these value.
Is it my reasoning correct?
How can I convert this entity query in a classic SQL query? Someone can help me?
Tnx
How can I convert this entity query in a classic SQL query?
To see actual SQL you can just call .ToString() method on your query;
var sql = (from x in context.VulnerabilityAlertDocuments select x.Severity).Average().ToString();
So I am executing a query on the VulnerabilityAlertDocuments DbSet
object that represent a query on my VulnerabilityAlertDocument table
on my database. Is it correct?
Yes
So what exatly do the previous query?
Your query will average value in Severity column of ValnerabilityAlertDocuments table.
your translated query would've looked simular to this:
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
AVG([Extent1].[Severity]) AS [A1]
FROM [dbo].[ValnerabilityAlertDocuments] AS [Extent1]
) AS [GroupBy1]
Also you could try to use such tool as SQL Server Profiler
UPDATE:
Just adding LinqPad to list of tools (thanks to Dismissile)
Select Average(x.Severity)
From VulnerabilityAlertDocuments x
Thats assuming your table is called "VulnerabilityAlertDocuments"
try again
I am studying that Linq to DataTable,Lambda.
Because is difficult want to change sql to linq,Lambda, is not doing.
Below the SQL code is member list that remove telephone number repetition.
I will thank if help.
SELECT A.no, B.name, B.userId, B.homeTel2
FROM
( SELECT homeTel2, min(no) NO
FROM OF_Member
GROUP BY homeTel2
) A
INNER JOIN OF_Member B
ON A.NO = B.NO
Progressing work ============
var objectName =from t in mMemberTable.AsEnumerable()
group t by t.Field("homeTel2")
Try this link:
Linq to Entities simple group query
converting ms sql “group by” query to linq to sql
var objectName =from t in mMemberTable.AsEnumerable()
group t by t.Field<string>("homeTel2") into groups
select groups;
Hope this helps,
Regards
Try using a tool called LINQ Pad. This is the best tool so far for writing and testing sql/LINQ queries and moreover it is free. It also allows you to convert your queries from LINQ to SQL and vice-versa.
http://www.linqpad.net