I have a SQL Statement that I am trying to convert to a LINQ query. I need to do this because I can\'t edit my database :(. Regardless, I have a SQL Statement that looks like th
The answer by BrokenGlass did not work for me when using Linq to Entities and resulted in an error stating "Unable to create a constant value of type 'MyEntity'. Only primitive types or enumeration types are supported in this context."
In order to overcome this I used the following:
var results = from x in context.MyEntities
join po in context.PurchaseOrders on x.CustomerID equals po.CustomerID into purchaseOrders
select new Customer()
{
CustomerID = x.CustomerID,
FirstName = x.FirstName,
LastName = x.LastName,
Gender = x.Gender,
BirthMonth = x.BirthMonth,
TotalPurchases = purchaseOrders.Count()
};
You can just nest the Linq to Entities query as well:
var results = from x in context.MyEntities
select new Customer()
{
CustomerID = x.CustomerID,
FirstName = x.FirstName,
LastName = x.LastName,
Gender = x.Gender,
BirthMonth = x.BirthMonth,
TotalPurchases = context.PurchaseOrders
.Where(po=>po.CustomerId == x.CustomerId)
.Count()
};
Just do a count off of the navigation property of "PurchaseOrders" that I assume is on the Customer entity.
TotalPurchases = x.PurchaseOrders.Count()