Linq to Sql 使用函数设置值

Linq to Sql Using a function to set a value

我想从数据库中获取一个 IEnumerable<T> 并在“Select”方法中使用一个函数来 return 一个 string 值。但我总是找回

'method cannot be translated into a store expression'

错误。

我已经查看了 Stack Overflow 上关于错误“LINQ to Entities 无法识别该方法....并且该方法无法转换为存储表达式”的所有 post

我发现绕过此错误的唯一方法是在查询具有 运行.

后应用该函数
void Main()
{
   int eventId = 17;

   IEnumerable<OccurrenceDropDownList> model = Occurrences.Select (s => new OccurrenceDropDownList
      {
         OccurrenceId = s.OccurrenceId,
         Name = s.Name
      })
      .AsEnumerable()
      .Select(m => new OccurrenceDropDownList
          {
             OccurrenceId = m.OccurrenceId,
             Name = m.Name,
             Selected = setSelected(m.OccurrenceId, eventId)
          }).AsEnumerable();

    foreach(var item in model)
    {
       Console.WriteLine(item.Name + " - id : " + item.OccurrenceId + " " + item.Selected); 
    }
}


public class OccurrenceDropDownList
{
        public int OccurrenceId { get; set; }
        public string Name { get; set; }
        public string Selected { get; set; }
}

static string setSelected(int occurrence, int selectedid){
    if(occurrence == selectedid){
        return "selected";
    }
    return "";
}

是否有任何方法可以将函数应用为第一个查询的结果?

应该更简单:

int eventId = 17;
IEnumerable<OccurrenceDropDownList> model = Occurrences
   .Select(s => new OccurrenceDropDownList
                    {
                       OccurrenceId = s.OccurrenceId,
                       Name = s.Name,
                       //magic ternary if
                       Selected = (eventId == s.OccurrenceId) ? "selected" : String.Empty
                    });

就是这样。我使用了应翻译为 SQL.

的三元 if 运算符