有一个名为MVCCrud的示例应用程序。这个例子非常好,我想将它用作我正在处理的项目的框架。
问题是MVCCrud使用LingToSQL而我想使用LinqToEntities。一旦我转换到除了一个地方之外的LinqToEntities,我得到的一切都能正常工作。
在以下代码中的行i = typeof(TModel).GetProperty(primaryKey).GetValue(p,null), cell = getCells(p) 它给出了Linq to Entities无法识别GetValue。
有人可以帮我重构以下代码吗?
items = items.OrderBy(string.Format("{0} {1}", sidx, sord)).Skip(pageIndex * pageSize).Take(pageSize).AsQueryable();
// Generate JSON
var jsonData =
new
{
total = totalPages,
page,
records = totalRecords,
rows = items.Select(
p => new
{
// id column from repository
i = typeof(TModel).GetProperty(primaryKey).GetValue(p, null),
cell = getCells(p)
}).ToArray()
};
return Json(jsonData);
这是getCell方法:
private string[] getCells(TModel p)
{
List<string> result = new List<string>();
string a = actionCell(p);
if (a != null)
{
result.Add(a);
}
foreach (string column in data_rows.Select(r => r.value))
{
try
{
// hack for tblcategory.name
string[] parts = column.Split('.');
// Set first part
PropertyInfo c = typeof(TModel).GetProperty(parts[0]);
object tmp = c.GetValue(p, null);
// loop through if there is more than one depth to the . eg tblCategory.name
for (int j = 1; j < parts.Length; j++)
{
c = tmp.GetType().GetProperty(parts[j]);
tmp = c.GetValue(tmp, null);
}
if (tmp.GetType() == typeof(DateTime))
{
result.Add(((DateTime)tmp).ToString(dateTimeFormat));
}
else if (tmp.GetType() == typeof(float))
{
result.Add(((float)tmp).ToString(decimalFormat));
}
else if (tmp.GetType() == typeof(double))
{
result.Add(((double)tmp).ToString(decimalFormat));
}
else if (tmp.GetType() == typeof(decimal))
{
result.Add(((decimal)tmp).ToString(decimalFormat));
}
else
{
result.Add(tmp.ToString());
}
}
catch (Exception)
{
result.Add(string.Empty);
}
}
return result.ToArray();
}
答案 0 :(得分:0)
执行此操作ToList()
而不是AsQueryable()
:
items = items.OrderBy(string.Format("{0} {1}", sidx, sord)).Skip(pageIndex * pageSize).Take(pageSize).ToList();
您无法在&#34;内执行任何外部方法&#34; linq查询。
你可以说这是在Linq2Sql中工作,然后你应该知道什么时候调用任何外部方法&#34;像ToString()
&#34; Linq2Sql将从数据库中获取所有数据,然后在内存中处理您的查询,如果您有大量记录,这可能会造成严重伤害。
有关详细信息,请查看this