在MVVM中,我从存储库获取一个实体集到viewmodel。在尝试访问实体的元素时,它会引发异常:
LINQ to Entities无法识别方法'InsurableRisk.Entities.QueriesParameter ElementAt [QueriesParameter](System.Linq.IQueryable`1 [InsurableRisk.Entities.QueriesParameter],Int32)'方法,而且此方法不能翻译成商店表达。
这是我的代码:
存储库:
public IQueryable<QueriesParameter> GetParams(int QKey)
{
IQueryable<QueriesParameter> param = (from Q in Context.QueriesParameters
where (Q.QueryKey == QKey)
select Q);
return param;
}
服务:
public IQueryable<QueriesParameter> GetParams(int QKey)
{
return _repository.GetParams(QKey);
}
视图模型:
paramLabel = new string[] { "ParamLabel1", "ParamLabel2", "ParamLabel3", "ParamLabel4", "ParamLabel5", "ParamLabel6" };
param = new string[] { "Param1", "Param2", "Param3", "Param4", "Param5", "Param6" };
paramVisibility = new string[] { "ParamVisiblity1", "ParamVisiblity2", "ParamVisiblity3", "ParamVisiblity4", "ParamVisiblity5", "ParamVisiblity6" };
paramLabelVisibility = new string[] { "ParamLabelVisiblity1", "ParamLabelVisiblity2", "ParamLabelVisiblity3", "ParamLabelVisiblity4", "ParamLabelVisiblity5", "ParamLabelVisiblity6" };
private Dictionary<int, string> m_queryNames;
private Dictionary<int, string> m_ReadOnlyQueryNames;
private int m_SelectedQueryNames;
public int SelectedQueryNames
{
get
{
return m_SelectedQueryNames;
}
set
{
if (m_SelectedQueryNames != value)
{
m_SelectedQueryNames = value;
OnPropertyChanged("SelectedQueryNames");
var QKey = m_SelectedQueryNames;
var sqlQuery = _service.GetQuery(QKey);
var paramCount = _service.GetParamCount(QKey);
//code to make the run button visible and the parameters to be visible
m_Visibility = true;
IQueryable<QueriesParameter> param = _service.GetParams(QKey);
for (int i = 1; i <= paramCount; i++)
{
OnPropertyChanged(paramLabelVisibility[i]);
OnPropertyChanged(paramVisibility[i]);
QueriesParameter qParam = param.ElementAt(i); <!-- I get the exception here -->
m_LabelName = qParam.ParameterName;
OnPropertyChanged(paramLabel[i]);
//OnPropertyChanged(param[i]);
}
}
}
为什么我收到此错误的任何帮助?
答案 0 :(得分:1)
您收到此错误是因为LINQ to Entities不支持ElementAt
(实际上,您将如何将其转换为SQL?)。以下是Supported and Unsupported LINQ Methods的列表。
您可以改为使用params:
IQueryable<QueriesParameter> param = _service.GetParams(QKey);
int i = 1; // btw why you are iterating from index 1? It should be zero!
foreach(var p in param)
{
OnPropertyChanged(paramLabelVisibility[i]);
OnPropertyChanged(paramVisibility[i]);
QueriesParameter qParam = p; // here
m_LabelName = qParam.ParameterName;
OnPropertyChanged(paramLabel[i]);
i++;
}
另一个选项 - 通过调用AsEnumerable()
或ToList()
将查询移至客户端。然后将使用Linq to Objects,您可以使用ElementAt(index)
方法或通过索引器[index]
:
List<QueriesParameter> param = _service.GetParams(QKey).ToList();
//... your code
QueriesParameter qParam = param[i];