开发者

How can i fill Anonymous type in list?

I try to write some codes about Generate list from Anonymous type via below codes :

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

But ERROR return me:

A primary key field specified via the KeyFieldName property is not found in the underlying data source. Make sure the field name is spelled correctly. Pay attention to the character case.

Main.cs


var Qry = from tableRaletions in taskMaints.TaskRelations
    where tableRaletions.TaskId == Co开发者_C百科nvert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
    select new
    {
        tableRaletions.RefMaintenance.code,
        tableRaletions.RefMaintenance.shortdesc
    };
GridMaintenanceData.DataSource = SetCalculatedTaskField.MakeList(Qry);
GridMaintenanceData.DataBind();


I don't see the point of your extension method as there is already a ToList extension method and that will create a list of your anymous type, what your method will do is create a list, with a single item in it that is an IQueryable of your anonymous type. Secondly the error is saying that GridMaintenanceData has a property called KeyFieldName and you have specified a fieldname in there that does not exist within the datasource you are binding to it, probably because of your silly MakeList method.

Do this instead:

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();


You've specified a KeyFieldName that does not exist in your DataSource. Exactly what the error says. As far as I can tell from your example, this is nothing to do with the population of your generic list.

From your example, I'm guessing your primary key is RelationId and your KeyFieldName is set to that property. So just change ensure RelationId is return in your select:

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


Here is your code:

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

What don't you use List<T> directly? What's the purpose for MakeList<T>? And

SetCalculatedTaskField.MakeList(Qry)

can be more easy:

Qry.ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜