Combining Linq and SQL query - c#

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.

Related

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

Construct a dynamic query (or algorithm) based on existing query

I have a task to construct a dynamic query (or algorithm) based on existing query with user choosed fields. Let me explain:
Lets say I have a function
ConstructQuery(string inputQuery, string[] mandatoryTables, string[] userFields) with 2 input parameters:
inputQuery: string query with many fields and tables, joins and where conditions
mandatoryTables: a list of mandatory tables
userFields: a list of fields that user choose in some web or desktop app
Function would have to return optimized query with tables and joins that are only needed for query to succeed.
inputQuery is for example constructed like this:
SELECT
Table1.SomeFieldA,
Table2.SomeFieldB,
Table2.SomeFieldC,
Table3.SomeFieldD
FROM Table1
JOIN Table2 ON Table1.Code = Table2.Code
JOIN Table3 ON Table2.Code = Table3.Code
WHERE Table1.SomeConditionField = "xyz"
userFields are: SomeFieldB, SomeFieldC
mandatoryTables: Table1
So the expected query is:
SELECT
Table2.SomeFieldB,
Table2.SomeFieldC
FROM Table1
JOIN Table2 ON Table1.Code = Table2.Code
WHERE Table1.SomeConditionField = "xyz"
My question is: is there a tool of some sort for solving this kind of problems or how you guys would solve it? I'm thinking of binary trees…
Regards,
Jani
This is something called join removal. This is (very) hard. Just parsing the query is nontrivial, then You'd have to analyze semantics, consider what are the unique keys, what are foreeign keys to have a chance to remove some tables. In Your example: the algorithm would have to know that table3.code is unique, and a foreign key to table2.code, otherwise the queries are not equivalent.
It could be easier to generate the right query in the first place. This is what some ORMs do.

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.

Mapping from relational database

For one to one relationships things are easy.
When it comes to one to many or many to many problems appear...
I am not using an ORM tool now for many reasons and i am wondering when i want to get data whether it is better to reassemble one to many relationship using multiple queries or in code..
For example.. Having a class Category and a class Product...
A product table has a collumn for category id (one category many products).
So for my full catalog is it better to execute 2 queries to get the categories and products i want and then populate for each category its products List ? (It is very easy with LINQ) ..
Or i should call query for each category ? Like select id from products where category_id=5;
Also i dont know how to name the functions like to set whether i want to fetch the other side of the relationship or not..
You should always use the least number of queries possible to retrieve your data. Executing one query per category to load the products is known as the N+1 problem, and can quickly cause a bottleneck in your code.
As far as what to name your methods that specify your fetch plans, name them after what the method actually does, such as IncludeProducts or WithProducts.
If you want to retrieve all categories and all their products, you can either select all categories and then select all products in two queries, or you can select in one query and group.
To use just one query, select an inner join for your two tables
SELECT c.*, p.*
FROM Category c INNER JOIN Product p ON c.CategoryId = p.CategoryId
and then construct business objects from the resulting dataset
result.GroupBy(r => r.CategoryId).Select(group =>
new Category(/* new Category using c.* columns */)
{
Products = /* new list of Products from p.* values */
});
But I have to ask - why aren't you using an ORM?

converting a SQL statement to LINQ query on a DataTable

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

Categories