Penguen
Penguen

Reputation: 17268

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 == Convert.ToInt32(txtID.Text) && tableRaletions.RelTypeId == 12
    select new
    {
        tableRaletions.RefMaintenance.code,
        tableRaletions.RefMaintenance.shortdesc
    };
GridMaintenanceData.DataSource = SetCalculatedTaskField.MakeList(Qry);
GridMaintenanceData.DataBind();

Upvotes: 0

Views: 1220

Answers (3)

Cheng Chen
Cheng Chen

Reputation: 43513

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

Upvotes: 0

djdd87
djdd87

Reputation: 68456

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
};

Upvotes: 1

Coding Flow
Coding Flow

Reputation: 21881

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

Upvotes: 1

Related Questions