converting a SQL statement to LINQ query on a DataTable - c#

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

Related

Whats the best solution to Entity Framework cores lack of moderate LINQ query support?

So basically I have a table containing a set of data. This data is then joined onto an organisation table to which multiple users can be apart of. Im then trying to get all files in the table where the user executing the query, has permission to access the organisation. To do this I'm using a where clause that checks the users permissions from the application, to the files that have them organisations linked. Im then selecting the top 100 results and counting the records returned. (I want to see if the user has access to 100+ files over all the organisations).
The problem is when I use the following LINQ query:
(from f in File
join o in Organisation on f.OrganisationId equals o.Id
where permissions.Contains(o.Id.ToString())
select f).Take(100).Count();
The take and the count aren't executed on the SQL server and are run in memory when I try a contains on a list which should convert to an IN (VALUES) query on SQL. I have 70,000+ File records and this is very slow and times out on a web server. This is expected as Entity Framework core is in early stages and does not support moderate or advanced LINQ queries yet.
My question is, is there a better alternative to raw SQL queries while still being able to filter by an array of items and still using Entity Framework core v1.1? Thanks.
Edit: I tried updating to the latest version, this still did not solve my issue as I still got the following output.
The LINQ expression '{permissions => Contains([o].Id.ToString())}' could not be translated and will be evaluated locally.
The LINQ expression 'Contains([o].Id.ToString())' could not be translated and will be evaluated locally.
The LINQ expression 'Take(__p_1)' could not be translated and will be evaluated locally.
The LINQ expression 'Count()' could not be translated and will be evaluated locally.
The warnings are misleading - the problem is the ToString() call which causes client evaluation of the query.
The following should produce the intended SQL query:
var idList = permissions.Select(int.Parse);
var result = (
from f in File
join o in Organisation on f.OrganisationId equals o.Id
where idList.Contains(o.Id)
select f).Take(100).Count();
which in my environment (EF Core v1.1.1) produces the following SQL with no warnings (as expected):
SELECT COUNT(*)
FROM (
SELECT TOP(#__p_1) [f].[Id], [f].[Name], [f].[OrganisationId]
FROM [Files] AS [f]
INNER JOIN [Organisations] AS [o] ON [f].[OrganisationId] = [o].[Id]
WHERE [o].[Id] IN (1, 3, 4)
) AS [t]

Combining Linq and SQL query

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.

How to convert this simple Entity Framework query into a standard SQL query?

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

How to convert SQL query with GROUP BY to LINQ Query

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

How to determine whether to use join in linq to sql?

I am just wondering about how we can determine whether to use join or not in linq to sql.
Eg. let say if we have two tables like this
Table 1 Customer
id
name
Table 2 addresstype
id
address1
customerid
and
var address = from cu in Customer
from ad in addresstype
where cu.id == ad.customerid
select ad;
or
var address = from cu in Customer
join ad in addresstype on cu.id equals ad.customerid
select de;
Is both way are the same. Is there any difference in performance?
Also the second method, will it come up with an error if there isn’t any matching?
Are you using linq to entities or linq to SQL? If its the former then you can avoid both of these by defining your relationships in the model and using navigation properties. This would be the clearest way of doing things
Basically, these two LINQ queries are equivalent to the following SQL queries:
select ad.*
from Customer cu, AddressType ad
where cu.ID == ad.CustomerID -- I assume this was meant by the OP
and
select ad.*
from Customer cu
inner join AddressType ad on cu.id = ad.CustomerID;
The difference between these two queries is mostly semantic, since the database will do the same thing in both cases and return a same result set for both queries.
I would prefer the join syntax in both SQL and LINQ since it defines an explicit relationship between the two tables/entities, that is only implied in the join-less version.
These are seems same query, they return same result but I don't know which one can be a faster, it should be bench marked.
But, In the case of linq2sql I prefer correlated subquery over join, because currently if you want t check the equation two element you should use syntax of:
new {X,Y} equals new {X',Y'}
in join and if you have more than this equations you should convert it to nested query. So I Prefer to have a more readable code which uses minimum differences in difference actions.
To throw a third and more prefered method into the mix with LINQ to SQL, use associations between the tables (even if you don't have them set up in your database). With that in place, you can navigate the object graph rather than using joins:
var query = from cu in Customer
from ad in cu.Addresses
select ad;
Note: when querying the object graphs, LINQ to SQL translates the join into a left outer join where-as the join/where syntax by default is an inner join.
Joins in LINQ should be used when there isn't a natural relationship between the objects. For example, use a join if you want to see the the listing of stores that are in the same city as your customers. (Join Customer.Address.City with Store.Address.City).
There should not be a difference between these two queries. I actually wondered this question myself a few months ago. I verified this through LINQPad. It's a free tool that you can download and actually see the generated SQL of any LINQ query (this is the query that is sent to the database).
The generated SQL should be the same for these two queries.
If you're doing this through Visual Studio, there is also a way you can see the generated SQL as well.

Categories