【发布时间】:2018-08-06 14:33:26
【问题描述】:
如何将绑定到匿名类型的网格视图中的数据项转换为由相同类型组成的类?我不断收到 InvalidCastException
这发生在 RowDataBound 中,使用
var row = (StationRow)e.Row.DataItem;
反对阶级:
class StationRow
{
public int StationID { get; set; }
public string Has_Had_Allocation { get; set; }
public string Inactive { get; set; }
public int Block { get; set; }
public int Session { get; set; }
public int Rotation { get; set; }
public int StationNumber { get; set; }
public string Remove_Station { get; set; }
}
(格式化的)错误是:
{"Unable to cast object of type '<>f__AnonymousType24`8
[System.Int32,
System.String,
System.String,
System.Int32,
System.Int32,
System.Int32,
System.Int32,
System.String]' to type 'StationRow'."}
我想我可以构建一个数据表并将 linq 结果泵入其中,然后绑定到表,使其成为 DataRowView,但这似乎效率低下,所以如果有人能指出我所缺少的,我将不胜感激。
【问题讨论】:
-
数据表是如何绑定的?为什么 ling 不投射到
StationRow项目而不是匿名类型? -
您不能只将匿名类型隐式转换为某些已知类型。您将需要mapping、explicit conversion 或其他方式。或者只是使用 StationRow 而不是 anon 类型开始。
-
要回答这个问题,没有办法仅仅因为属性名称对齐就转换为不同的类型。
-
为什么要创建匿名类型对象而不是直接创建
StationRow对象? -
@GertArnold 如果您将其放入答案中,我会将其标记为正确
标签: c# asp.net linq-to-entities anonymous-types