I have a SQL Query and I wanted to convert into LINQ can you please help to do this.
SELECT p.ProductID, p.ProductName FROM tblProducts p
WHERE p.ProductID IN (SELECT s.ProductID FROM tblStock s WHERE s.BarCode = 2222)
In this case BarCode is a null able type.
Use Contains to translate to 'IN':
tblProducts.Where(p => tblStock.Where(ts => ts.BarCode == 2222)
.Select(ts => ts.ProductId)
.Contains(p.ProductID))
.Select(p => new {p.ProductID, p.ProductName});
You should join instead of in:
var result = tblProducts
.Join
(
tblStock.Where(s => s.BarCode = 2222),
p => p.ProductID,
s => s.ProductID,
(p, s) => new { ProductID = p.ProductID, ProductName = p.ProductName }
);
Depending on your data and needs, you could also add .Distinct().
This should be written as an inner join for efficiency. In Linq:
var myQuery = from p in myContext.tblProducts
join s in myContext.tblStock on p.ProductID equals s.ProductID
where s.BarCode = 2222
select new { ProductID = p.ProductID, ProductName = p.ProductName };
foreach(var product in myQuery)
{
// do stuff
}
Related
Is it possible to do the following in linq, where in my select new I use the value from TotalOrderItems as part of the calculation for TotalInStockItems?
var Order = (from o in orderItems
select new ShippingOrder { OrderId = orderItems.OrderId
TotalOrderItems = orderItems.GroupBy(x => x.Sku).Count(),
TotalInStockItems = TotalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(),
}).ToList();
try using the let clause (C# Reference) to store the value for use later in the query
(from o in orderItems
let totalOrderItems = orderItems.GroupBy(x => x.Sku).Count()
select new ShippingOrder {
OrderId = o.OrderId
TotalOrderItems = totalOrderItems,
TotalInStockItems = totalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(),
}).ToList();
How do I simplified the below statement?
var Orders = db.Orders
.Include(o => o.shipment)
.Where(o => o.ID == 3 || o.ID == 5 || o.ID == 10)
.ToList();
Ultimately, I would like to do like:
SELECT * FROM Orders WHERE ID IN (3,5,10)
in strongly typed Entity to return to View model
I've tried .Any, .Contains or .Intersect but cannot "form" the Linq query.
Something like this?
var items = new int[] {3,5,10};
var Orders = db.Orders
.Include(o => o.shipment)
.Where(o => items.Contains(o.ID))
.ToList();
How about this ?
List<int> items = new List<int>(new []{3,5,10});
var Orders = db.Orders
.Include(o => o.shipment)
.Where(o => items.Contains(o.ID))
.ToList();
In place of int you should use the same datatype as of ID
Hope it helps!!!
The EntityModel is defined as:
Personnel has a link to a Country
When executing this code in LinqPad, I see that the SQL which is generated is not optimized (all fields are returned) in the first query ? What am I missing here or doing wrong ?
Query 1 LINQ
var Country = Countries.FirstOrDefault(o => o.Id == 100000581);
var personnelIds = Country.Personnels.Select(p => p.Id).ToArray();
personnelIds.Dump();
Query 1 SQL
exec sp_executesql N'SELECT [t0].[Id], [t0].[Version], [t0].[Identifier], [t0].[Name], , [t0].[UpdatedBy] FROM [Personnel] AS [t0] WHERE [t0].[Country_Id] = #p0',N'#p0 bigint',#p0=100000581
Query 2 LINQ
var Country = Countries.FirstOrDefault(o => o.Id == 100000581);
var personnelIds2 = Personnels.Where(p => p.Country == Country).Select(p => p.Id).ToArray();
personnelIds2.Dump();
Query 2 SQL
exec sp_executesql N'SELECT [t0].[Id] FROM [Personnel] AS [t0] WHERE [t0].[Country_Id] = #p0',N'#p0 bigint',#p0=100000581
The database used is SQL Express 2008. And LinqPad version is 4.43.06
//var Country = Countries.FirstOrDefault(o => o.Id == 100000581);
var personnelIds = context.Personnels
.Where(p => p.Country.Id == 100000581)
.Select(p => p.Id)
.ToArray();
personnelIds.Dump();
Try this, it should be better.
Personnels collection will be populated via lazy loading when accessed, hence retrieving all of the fields from the DB. Here's what's happening...
// retrieves data and builds the single Country entity (if not null result)
var Country = Countries.FirstOrDefault(o => o.Id == 100000581);
// Country.Personnels accessor will lazy load and construct all Personnel entity objects related to this country entity object
// hence loading all of the fields
var personnelIds = Country.Personnels.Select(p => p.Id).ToArray();
You want something more like this:
// build base query projecting desired data
var personnelIdsQuery = dbContext.Countries
.Where( c => c.Id == 100000581 )
.Select( c => new
{
CountryId = c.Id,
PersonnelIds = c.Personnels.Select( p => p.Id )
}
// now do enumeration
// your example shows FirstOrDefault without OrderBy
// either use SingleOrDefault or specify an OrderBy prior to using FirstOrDefaul
var result = personnelIdsQuery.OrderBy( item => item.CountryId ).FirstOrDefault();
OR:
var result = personnelIdsQuery.SingleOrDefault();
Then get the array of IDs if not null
if( null != result )
{
var personnelIds = result.PersonnelIds;
}
Try can also try grouping personnel into a single query
var groups =
(from p in Personnel
group p by p.CountryId into g
select new
{
CountryId = g.Key
PersonnelIds = p.Select(x => x.Id)
});
var personnelIds = groups.FirstOrDefault(g => g.Key == 100000581);
Do you have the ForeignKey explicitly defined in your POCO for Personnel? It's common to leave it out in EF, but adding it would massively simplify both this code and the resulting SQL:
public class Personnel
{
public Country Country { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
. . .
}
> update-database -f -verbose
var ids = db.Personnel.Where(p => p.CountryId == 100000581).Select(p => p.Id).ToArray();
How can I convert this LINQ query from query syntax to method syntax? I am performing a co-related query operation.
var query = (from r in objEntities.Employee
where r.Location == (from q in objEntities.Department
where q.Location == r.Location
select q.Location).FirstOrDefault()
select new
{
FirstName = r.FirstName,
LastName = r.LastName,
Age = r.Age,
Location = r.Location
});
GridView1.DataSource = query;
GridView1.DataBind();
I think you are trying to convert the query to method-based query instead of syntax-based query.
var query = objEntities.Employee
.Where(e => e.Location == objEntities.Department
.Where(d => d.Location == r.Location)
.Select(d => d.Location)
.FirstOrDefault())
.Select(e => new {
FirstName = e.FirstName,
LastName = e.LastName,
Age = e.Age,
Location = e.Location
});
I'm also pretty sure your inner expression within where clause could be replaced with something like that:
.Where(e => objEntities.Department.Any(d => d.Location == e.Location)
Nested queries always have performance issue instead you should use join:
In the lambda expression query should be
var query = objEntities.Employee.Join(objEntities.Department, E => E.Location,
D => D.Location,
(E,D) => new {
FirstName = E.FirstName,
LastName = E.LastName,
Age = E.Age,
Location = E.Location
});
Can anyone show me two simple examples of joining 2 and 3 tables using LAMBDA EXPRESSION(
for example using Northwind tables (Orders,CustomerID,EmployeeID)?
Code for joining 3 tables is:
var list = dc.Orders.
Join(dc.Order_Details,
o => o.OrderID, od => od.OrderID,
(o, od) => new
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
ShipName = o.ShipName,
Quantity = od.Quantity,
UnitPrice = od.UnitPrice,
ProductID = od.ProductID
}).Join(dc.Products,
a => a.ProductID, p => p.ProductID,
(a, p) => new
{
OrderID = a.OrderID,
OrderDate = a.OrderDate,
ShipName = a.ShipName,
Quantity = a.Quantity,
UnitPrice = a.UnitPrice,
ProductName = p.ProductName
});
Thanks
try this one to join 2 tables using lambda expression
var list = dataModel.Customers
.Join( dataModel.Orders,
c => c.Id,
o => o.CustomerId,
(c, o) => new
{
CustomerId = c.Id,
CustomerFirstName = c.Firstname,
OrderNumber = o.Number
});
public void Linq102()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}