linq expression error:cant display column? - linq

i am trying to join my linq query with another table. How can I display the name in the Customer table? I am getting an error: does not contain a definition for 'Name'?
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group p by p.Date.Year into SalesPerYear
select new {
customername= SalesPerYear.First().Name,
customerid= SalesPerYear.First().CustomerID,
totalsales= SalesPerYear.Sum(x=>x.Price)
}

You're grouping p (i.e. purchases) by date - so the customer details are no longer present.
Try this instead:
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group new { p, c } by p.Date.Year into SalesPerYear
select new {
CustomerName = SalesPerYear.First().c.Name,
CustomerId = SalesPerYear.First().p.CustomerID,
TotalSales = SalesPerYear.Sum(x => x.p.Price)
}
Or alternatively:
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group new { p.CustomerId, p.Price, c.CustomerName }
by p.Date.Year into SalesPerYear
select new {
SalesPerYear.First().CustomerName,
SalesPerYear.First().CustomerId
TotalSales = SalesPerYear.Sum(x => x.Price)
}

SalesPerYear is an IGrouping. You need to access Name, CustomerID etc off the Value property of the IGrouping.

Related

Linq Where clause with two conditions, not working

I have three tables:
[Products]
Id
Title
Info
Price
[ProductCategories]
Id
Title
ParentId
[ProductsInCategories]
Id
ProductId
ProductCategoryId
I'm trying to read a selection of products in a certain category. The code I have doesn't concider the ProductCategoryId, and just loads all products from the Product table. Where's my mistake?:
The id-variable is a method argument. The value coming in is correct.
var ProdInCat = from p in _context.Products
from pc in _context.ProductsInCategories
.Where(x => p.Id == x.ProductId && x.ProductCategoryId == id)
.DefaultIfEmpty()
select new
{
p.Id,
p.Title,
p.Info,
p.Price
};
You can join products with a filtered list of products in categories based on your external (computed) id.
from p in _context.Products
join pc in _context.ProductsInCategories.Where(pic => pic.ProductCategoryId == id).DefaultIfEmpty()
on p.Id equals pc.ProductId
More about how can you achieve this at the following link: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause
Use Inner join expression
var ProdInCat = from p in _context.Products
from pc in _context.ProductsInCategories.Where(x => x.ProductCategoryId == id).DefaultIfEmpty()
on p.Id equals pc.ProductID
select new {
p.Id,
p.Title,
p.Info,
p.Price
};

CRM 2011- LINQ query joining Account, Case and Activity entity

I try to make the following query using Account, Case and Activity entities :
*var findCases =
from a in context.AccountSet
join c in context.IncidentSet
on a.AccountId equals c.CustomerId.Id
join p in context.ActivityPointerSet
on c.Id equals p.RegardingObjectId.Id
select new
{
TicketNumber = c.TicketNumber,
IncidentId = c.IncidentId,
CreatedOn = c.CreatedOn,
StateCode = c.StateCode,
AccountName = a.Name
};*
The execution of this query gives the error:
AttributeFrom and AttributeTo must be either both specified or both ommited. You can not pass only one or the other. AttributeFrom: , AttributeTo: regardingobjectid
Any suggestion will be appreciated.
Regards.
Radu Antonache
Remove CasesForAccount from the query..
*var findCases =
from a in context.AccountSet
join c in context.IncidentSet
on a.AccountId equals c.CustomerId.Id
join p in context.ActivityPointerSet
on c.Id equals p.RegardingObjectId.Id
select new
{
TicketNumber = c.TicketNumber,
IncidentId = c.IncidentId,
CreatedOn = c.CreatedOn,
StateCode = c.StateCode,
AccountName = a.Name
};*

LINQ Query using 3 tables to get grouped data

So I am trying to get a list of cities and the name of the best sold product in each city. There are 3 tables and I cant seem to group them properly and get the count.
Here is what I have so far:
var result9 = (from p in shop.Tb_Purchases
join c in shop.Tb_PreferredCustomer on p.Cust_ID equals c.Cust_ID
join ap in shop.Tb_AvailableProduct on p.Prod_ID equals ap.Prod_ID
group ap by new { c.City, ap.Name } into g
select new { City = g.Key.City, Name = g.Key.Name, NumOf = g.Count() }).ToList();
and this gives me every product sold in each city and how many of them were sold, however i need only one city and the one product that was sold the most in it.
One solution is to group by just the city and then find each city's best product in a subquery.
var result9 = (from p in shop.Tb_Purchases
join c in shop.Tb_PreferredCustomer on p.Cust_ID equals c.Cust_ID
join ap in shop.Tb_AvailableProduct on p.Prod_ID equals ap.Prod_ID
group ap by c.City into g
let largestProductGroup = g.GroupBy(x => x.Name)
.OrderByDescending(x => x.Count())
.First()
select new
{
City = g.Key.City,
Name = largestProductGroup.Key.Name,
NumOf = largestProductGroup.Count()
}).ToList();

Group by, Sum, Join in Linq

I have this simple sql query:
select c.LastName, Sum(b.Debit)- Sum(b.Credit) as OpenBalance from Balance as b
inner join Job as j on (b.Job = j.ID)
inner join Client as c on (j.Client = c.ID)
Group By c.LastName
and I am trying to convert it to work in linq like this:
from b in Balance
join j in Job on b.Job equals j.ID
join c in Client on j.Client equals c.ID
group b by new { c.LastName } into g
select new {
Name = c.Lastname,
OpenBalance = g.Sum(t1 => t1.Credit)
}
but when I try to run it in LINQPad I get the following message:
The name 'c' does not exist in the
current context
and it highlights c.Lastname in select new statement.
Any help on this will be greatly appreciated.
Thank you.
Well, you've grouped b by c.LastName. So after the grouping operation, you're dealing with g which is a grouping with the element type being the type of b, and the key type being the type of c.LastName. It could well be that all you need is:
select new {
Name = g.Key,
OpenBalance = g.Sum(t1 => t1.Credit)
}
... but if you need to get at any other aspects of c, you'll need to change your grouping expression.

linq nested query

I have a query that has the following
var myvar = from table in MyDataModel
where.....
select new MyModel
{
modelvar1 = ...,
modelvar2 = (from..... into anothervar)
}
What I want to do is have modelvar2 be a join between the result I currently get from anothervar with another table in MyDataModel.
Thanks
The parenthesis looks more like a subquery than a join. This is how you do a join.
Example tables from the AdventureWorks database.
using (DataClasses1DataContext context = new DataClasses1DataContext())
{
// If you have foreign keys correctly in your database you can
// join implicitly with the "dot" notation.
var myvar = from prod in context.Products
where prod.ListPrice < 10
select new
{
Name = prod.Name,
Category = prod.ProductSubcategory.ProductCategory.Name,
};
// If you don't have foreign keys you need to express the join
// explicitly like this
var myvar2 = from prod in context.Products
join prodSubCategory in context.ProductSubcategories
on prod.ProductSubcategoryID equals prodSubCategory.ProductSubcategoryID
join prodCategory in context.ProductCategories
on prodSubCategory.ProductCategoryID equals prodCategory.ProductCategoryID
where prod.ListPrice < 10
select new
{
Name = prod.Name,
Category = prodCategory.Name,
};
// If you REALLY want to do a subquery, this is how to do that
var myvar3 = from prod in context.Products
where prod.ListPrice < 10
select new
{
Name = prod.Name,
Category = (from prodSubCategory in context.ProductSubcategories
join prodCategory in context.ProductCategories
on prodSubCategory.ProductCategoryID equals prodCategory.ProductCategoryID
select prodCategory.Name).First(),
};
// If you want to get a list from the subquery you can do like this
var myvar4 = from prodCategory in context.ProductCategories
select new
{
Name = prodCategory.Name,
Subcategoreis = (from prodSubCategory in context.ProductSubcategories
where prodSubCategory.ProductCategoryID == prodCategory.ProductCategoryID
select new { prodSubCategory.ProductSubcategoryID, prodSubCategory.Name }).ToList(),
};
}
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [Orders] AS [t0]
INNER JOIN ([Order Details] AS [t1]
INNER JOIN [Products] AS [t2] ON [t1].[ProductID] = [t2].[ProductID]) ON [t0].[OrderID] = [t1].[OrderID]
can be write as
from o in Orders
join od in (
from od in OrderDetails join p in Products on od.ProductID equals p.ProductID select od)
on o.OrderID equals od.OrderID
select o

Resources