繁体   English   中英

如何在列表中填写匿名类型?

[英]How can i fill Anonymous type in list?

我尝试通过以下代码编写一些有关从匿名类型生成列表的代码:

public static List<T> MakeList<T>(T itemOftype)
{
    List<T> newList = new List<T>();
    newList.Add(itemOftype);
    return newList;
}

但是错误返回我:

在基础数据源中找不到通过KeyFieldName属性指定的主键字段。 确保字段名称拼写正确。 注意字符大小写。

Main.cs


var Qry = from tableRaletions in taskMaints.TaskRelations
    where tableRaletions.TaskId == Convert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
    select new
    {
        tableRaletions.RefMaintenance.code,
        tableRaletions.RefMaintenance.shortdesc
    };
GridMaintenanceData.DataSource = SetCalculatedTaskField.MakeList(Qry);
GridMaintenanceData.DataBind();

我看不到扩展方法的要点,因为已经有一个ToList扩展方法,它将创建任何类型的列表,您的方法将执行的操作是创建一个列表,其中包含一个可查询的项您的匿名类型。 其次,错误是说GridMaintenanceData具有一个名为KeyFieldName的属性,并且您在其中指定了一个字段名,该字段名在您绑定到它的数据源中不存在,这可能是因为您的MakeList方法很愚蠢。

改为:

var Qry = from tableRaletions in taskMaints.TaskRelations
    where tableRaletions.TaskId == Convert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
    select new
    {
        tableRaletions.RefMaintenance.code,
        tableRaletions.RefMaintenance.shortdesc
    };
GridMaintenanceData.DataSource = Qry.ToList();
GridMaintenanceData.DataBind();

您指定的KeyFieldName在您的数据源中不存在。 究竟错误是什么。 据我从您的示例可以看出,这与泛型列表的填充无关。

从您的示例中,我猜您的主键是RelationIdKeyFieldName设置为该属性。 因此,只需更改以确保您选择的RelationId已返回:

select new
{
    tableRaletions.RefMaintenance.RelationId // It's spelt `relations` by the way.
    tableRaletions.RefMaintenance.code,
    tableRaletions.RefMaintenance.shortdesc
};

这是你的代码:

public static List<T> MakeList<T>(T itemOftype)
{
    List<T> newList = new List<T>();
    newList.Add(itemOftype);
    return newList;
}

您不直接使用List<T>什么? MakeList<T>的目的是什么?

SetCalculatedTaskField.MakeList(Qry)

可以更容易:

Qry.ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM