LINQ - Nested Query

前端 未结 3 912
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 03:13

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

相关标签:
3条回答
  • 2021-01-21 03:22

    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()
                  };
    
    0 讨论(0)
  • 2021-01-21 03:26

    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()
                  };
    
    0 讨论(0)
  • 2021-01-21 03:40

    Just do a count off of the navigation property of "PurchaseOrders" that I assume is on the Customer entity.

    TotalPurchases = x.PurchaseOrders.Count()
    
    0 讨论(0)
提交回复
热议问题