Convert Datatable to List Entity

Asked

Viewed 241 times

1

I’m trying to use the code below to convert but it gives error everywhere that has the T and where. What could be?

// function that set the given object from the given data row
public static void SetItemFromRow(T item, DataRow row)
    where T : new()
{
    // go through each column
    foreach (DataColumn c in row.Table.Columns)
    {
        // find the property for the column
        PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

        // if exists, set the value
        if (p != null && row[c] != DBNull.Value)
        {
            p.SetValue(item, row[c], null);
        }
    }
}

// function that creates an object from the given data row
public static T CreateItemFromRow(DataRow row)
    where T : new()
{
    // create a new object
    T item = new T();

    // set the item
    SetItemFromRow(item, row);

    // return 
    return item;
}

// function that creates a list of an object from the given data table
public static List CreateListFromTable(DataTable tbl)
    where T : new()
{
    // define return list
    List lst = new List();

    // go through each row
    foreach (DataRow r in tbl.Rows)
    {
        // add to the list
        lst.Add(CreateItemFromRow(r));
    }

    // return the list
    return lst;
}

Veja o erro

  • I may be wrong, but T is what? The compiler doesn’t know what T is, I think that’s why it makes the mistake. Different from a generic list with generic type T. If I’m wrong please correct me.

1 answer

1

The syntax is wrong. The generic usage statement is as follows:

public static void SetItemFromRow<T>(T item, DataRow row)
    where T : class, new()
{

...

public static T CreateItemFromRow<T>(DataRow row)
    where T : class, new()
{

new() indicates to the code that the class in question has a null constructor, so it can be instantiated within the method.

Doesn’t have to be exactly class the definition. It can be a class or an interface (the compiler will understand that T is a class that implements that interface).

  • Foul <T> in the signature of methods to indicate that they are generic: public static void SetItemFromRow<T>(T item, DataRow row). Restriction is also not required class, unless we want to restrict T only the Reference types, what I think is not the case here.

  • @Corrected as per your guidance. Thank you. About Reference types, I do not believe that, as the author of the question put it, the use of the methods will be very comprehensive. I believe that class already solve well the issue.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.