SQL query to linq syntax - c#

How can i convert this join stmnt to linq syntax
SELECT pv.Product_ID, pv.Product, v.Add_ID, v.Product_ID
FROM Product AS pv
JOIN Product_Add AS v
ON ((pv.Product_ID = v.Add_ID) OR (pv.Product_ID = v.Product_ID))
where(( pv.Product_ID = v.Product_ID) OR (pv.product_ID = v.Add_ID))
Thanks

I would convert this for you
but its better you use this tool which is really help full to me to convert sql to linq code
http://www.sqltolinq.com/
just download and install on your machine will do work for you.

Instead of Join, you can use from...where, it's the same thing.
from pv in Product
from v in Product_Add
where ((pv.Product_ID == v.Add_ID) || (pv.Product_ID == v.Product_ID))
&&(( pv.Product_ID = v.Product_ID) || (pv.product_ID = v.Add_ID))
(You just AND all the join conditions with the rest of the where if you have multiple joins)

Related

Converted my SQL to LINQ and I am getting System.InvalidOperationException: Client side GroupBy is not supported error

I am getting Unhandled exception. System.InvalidOperationException: Client side GroupBy is not supported when I try to run this LINQ Query in my C# application using EntityFrameworkCore.
This is my LINQ Query.
var test =
(from lbls1 in ctxt.Labels
join att in ctxt.Attributes
on lbls1.Id equals att.LabelId
join img in ctxt.Images
on lbls1.ImageId equals img.Id
where att.plate_region_conf >= min_region_conf
&& att.plate_code_conf >= min_code_conf
&& states.Contains(att.plate_state)
&& cameraid.Contains(img.CameraId)
&& !exclude_filename.Contains(img.Filename)
group lbls1 by new {
att.plate_code,
att.plate_state
} into lbls1
select lbls1).ToList()
This is the original SQL query I created and ran.
Select ImageId FROM Labels as l JOIN Attributes as a ON
a.LabelID = l.Id
JOIN Images as I
On l.ImageId = I.Id
Where
plate_state = states
AND plate_region_conf >= region_conf
AND plate_code_conf >= code_conf
AND plate_stacked = stacked
AND is_edge = edge
AND I.CameraId = cameraid
AND I.Filename <> filename
Group By plate_code, plate_state;
What I read, Client-side evaluation was removed from LINQ but this should still work if this code translate to SQL. I am running MySQL and I did removed ONLY_FULL_GROUP_BY so it should work.Any advice would be appreciated!
You have used SelectMany, which introduce rows duplication. Instead of that you have to use Any function in predicate and navigation property, I hope you have them.
var query =
from label in ctxt.Labels
where
label.Attributes.Any(att =>
att.plate_region_conf >= min_region_conf
&& att.plate_code_conf >= min_code_conf
&& states.Contains(att.plate_state)
)
&& cameraid.Contains(label.Image.CameraId)
&& !exclude_filename.Contains(label.Image.Filename)
select label;
If Label to Image is One to Many relation, you also has to use Any.

SQL to Linq/Lambda

Anyone can help me how to convert sql statement to linq and lambda like this ?
SELECT
tbl_terms.ID,
tbl_terms.Terms
FROM
tbl_terms
LEFT JOIN tbl_asn_uploaddoc ON tbl_terms.ID != tbl_asn_uploaddoc.Id_term
WHERE
tbl_asn_uploaddoc.Nip = '201948274838491943' && tbl_asn_uploaddoc.STATUS = 1
Thanks in advance
LINQ is mostly similar to SQL if you use query syntax instead of method syntax. Here is what I could gather quickly. Can't test because I don't have your model classes.
var Result = from t in context.tbl_terms
join d in context.tbl_asn_uploaddoc on t.ID != d.Id_term
where d.Nip = '201948274838491943' && d.STATUS = 1
select t.ID, t.Terms
Use below query that will give you LEFT JOIN on both of your entity,
var result = (from t in _con.tbl_Terms
join u in _con.tbl_asn_uploaddocs on t.ID equals u.Id_term
into tu
where !tu.Any()
from u in tu.DefaultIfEmpty()
where u.Nip == "201948274838491943" && u.STATUS == 1
select new
{
ID = t.ID,
Terms = t.Terms
}).ToList();
Where _con is your context.
You can use SQL to LINQ converter tool Linqer
Linqer is a SQL to LINQ conversion tool. It helps learning LINQ and convert existing SQL statements.

Use Array in Linq query

My question got down voted and put on hold because it is not specific enough. Ill try to specify
Before linq I would do this query
sql="SELECT products.* FROM products INNER JOIN productaccess ON products.id=productaccess.productid"
Now with the entity framework and link I can do this
var products = (from lProducts in db.Products
join lProductAccess in db.ProductAccess on lProducts.ID equals lProductAccess.ProductID
select lProducts).ToList();
But what if I want the flexibilty to get all products or only get the accessible objects
In sql I can do this
sql="SELECT products.* FROM products "
if (useProductAccess) {
sql+=" INNER JOIN productaccess ON products.id=productaccess.productid"
}
In Linq I have to make a separate linq statement.
if (useProductAccess) {
var productsFiltered = (from lProducts in db.Products
join lProductAccess in db.ProductAccess on lProducts.ID equals lProductAccess.ProductID
select lProducts).ToList();
} else {
var productsAll = (from lProducts in db.Products select lProducts).ToList();
}
Now, I could just get all the lProducts and then filter it in an additional linq statement with lProductAccess but then I am using an unnecessary large amount of data.
Is it an option to use:
var productsAccecible = (from lProductAccess in db.ProductAccess where lProductAccess.CustID==custID select lProductAccess).toArray();
var products = (from lProducts in db.Products
where (useProductAccess ?
productsAccessible.Contains(lProducts.ID)
: true)
select lProducts).ToList();
Linq provider will not know how to transform the ternary operator (? and :) in a valid sql, you could try this:
var query = db.Products;
if (useProductAccess)
query = query.Where(p => productsAccessible.Contains(p.ID));
var result = query.ToList();
I used the express profiler to see how the linq statement is translated into sql. It shows that the
productsAccessible.Contains(lProducts.ID)
part gets translated as
products.id in (comma seperated list of values)
My conclusion is it will work fine.
Are there possible drawbacks
Sure - it may produce an inefficient query, or it may not even work.
One thing to note is that your conditional operator won't compile; you can't return a bool and an int from the ternary operator.
Maybe you mean:
var products = (from lProducts in db.Products
where (useProductAccess ?
productsAccessible.Contains(lProducts.ID)
: true)
select lProducts).ToList();
or build your query up using method syntax and only add the where clause if necessary.

SQL to LINQ conversion problems

I have a SQL query, which i know works as expected. But i need it to be LINQ which i use to interact with the database. The SQL query is:
SELECT * FROM motorposition, experimentmotor, motors
WHERE motorposition.motorid = experimentmotor.motorid
AND experimentmotor.experimentid = 13
AND motors.id = experimentmotor.motorid
I have almost no experience with LINQ. Is it even possible to do this in LINQ?
The code would be something like this:
var results = from mp in yourcontext.motorposition
join e in yourcontext.experimentmotor on mp.motorid equals e.motorid
join m in yourcontext.motors on e.motorid equals m.motorid
where e.experimentid == 13
select new {mp, e, m};

Converting an advanced query from SQL to LINQ

Still getting used to LINQ syntax, and have come across this query that I need to create in LINQ - but not exactly sure how.
SELECT *,
(SELECT 1 FROM Applications
WHERE Applications.jID = Jobs.ID
AND Applications.uID = #uID) AS Applied
FROM [Jobs]
Playing in LinqPad, but the interface isn't really helping (at least with what I can see).
Based on the link provided by Paul Sasik, and his advice that you're after a LEFT OUTER JOIN, this query should meet your requirements;
var query = from job in jobs
join app in applications on job.ID equals app.jID into grouped
from subApp in grouped.DefaultIfEmpty()
select new { Job = job, Applied = (subApp != null) };
EDIT:
To filter by user, update the query as follows;
var query = from job in jobs
join app in
(
from userApp in applications where userApp.uID == uID select userApp
) on job.ID equals app.jID into grouped
from subApp in grouped.DefaultIfEmpty()
select new { Job = job, Applied = (subApp != null) };
I personally would have reverted to just using the .Where() method directly at this point, but just thought I'd keep everything consistent and continue using the query syntax.
var jobs = from j in this.db.Jobs
where !j.Applications.Any(x => x.UserId == currentUserId)
select j;
I recommend checking out the tool Linqer -- which converts SQL to Linq code. It's not free but there is a 10 day trial.

Categories