我想从数据库IEnumerable<T>
和'Select
'方法中使用函数返回string
值。但我总是回到
'方法无法转换为商店表达式'
错误。
我已经看过Stack Overflow关于错误的所有帖子'LINQ to Entities无法识别方法....并且此方法无法转换为商店表达式“
我发现解决此错误的唯一方法是在查询运行后应用该函数。
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 "";
}
有没有办法将该函数作为第一个查询的结果应用?
答案 0 :(得分:1)
应该更简单:
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运算符。