开发者

LINQ query returning a List<> as a class member

开发者 https://www.devze.com 2023-01-25 19:27 出处:网络
Given the follow data class, public class EmployeeMenu { public int ID { get; set; } public string HeaderName { get; set; }

Given the follow data class,

 public class EmployeeMenu
 {
  public int ID { get; set; }
  public string HeaderName { get; set; }
  public List<string> ItemNames { get; set; }
 }

how can I get a sub-query into the ItemNames field?

My current query of

 IQueryable<EmployeeMenu> retValue =
  from mh in menuHeaders
  select new EmployeeMenu
  {
 开发者_C百科  ID = mh.ID,
   HeaderName = mh.HeaderName,
   ItemNames = (from mhi in mh.MenuItems
       select mhi.MenuItemName).ToList<string>()
  };

doesn't seem to be doing the trick...

The data structure is

MenuHeaders        MenuItems
-----------        ---------
ID                 ID
HeaderName <-(FK)--MenuHeaderID
                   MenuItemName


I ended up just changing from a List to IEnumerable. This fixed it.


Wouldnt you want to just put a where in your sub-select to filter that down to all the menu items with the MenuHeaderID equals mh.HeaderName. You can just .Equals() with the StringComparison type if you want as well.

Here is an example...

    IQueryable<EmployeeMenu> retValue = 
  from mh in menuHeaders 
  select new EmployeeMenu 
  { 
   ID = mh.ID, 
   HeaderName = mh.HeaderName, 
   ItemNames = (from mhi in mh.MenuItems 
       select mhi.MenuItemName where mhi.MenuHeaderID = mh.HeaderName).ToList<string>() 
  }; 


My guess is that your not initiliazing the list within your class. I basing this off the experience I was having with Nhibernate.

public class EmployeeMenu
 {
  public int ID { get; set; }
  public string HeaderName { get; set; }
  public List<string> ItemNames { get; set; }

  public EmployeeMenu()
  {
       ItemNames=new List<string>();
   }
 }

Hope this helps.


Okay. Try replacing

(from mhi in mh.MenuItems
 select mhi.MenuItemName).ToList<string>()

by

mh.MenuItems
  .AsEnumerable()
  .Select(mhi => mhi.MenuItemName)
  .ToList()

I question if you want a where clause in there somewhere, but this should get you past the runtime exception.

Any time you see an error message of the form "LINQ to Entities does recognize the method ... and this method can not be translated into a store expression" LINQ to Entities is telling you that it can't figure out how to translate part of the expression tree into a SQL statement. This means you need to pull things client side so that LINQ to Entities doesn't try to translate something that it can't translate.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号