SORU
31 Mart 2009, Salı


.NET - Genel Toplama DataTable Dönüştürmek

Bir DataTable için genel bir toplama (Liste) dönüştürmek için çalışıyorum. Aşağıdaki kod bana bu konuda yardımcı buldum:

// Sorry about indentation
public class CollectionHelper
{
private CollectionHelper()
{
}

// this is the method I have been using
public static DataTable ConvertTo<T>(IList<T> list)
{
    DataTable table = CreateTable<T>();
    Type entityType = typeof(T);
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

    foreach (T item in list)
    {
        DataRow row = table.NewRow();

        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item);
        }

        table.Rows.Add(row);
    }

    return table;
}    

public static DataTable CreateTable<T>()
{
    Type entityType = typeof(T);
    DataTable table = new DataTable(entityType.Name);
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

    foreach (PropertyDescriptor prop in properties)
    {
        // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES
        table.Columns.Add(prop.Name, prop.PropertyType);
    }

    return table;
}
}

Benim sorunum null olabilecek bir tür MySimpleClass özelliklerinden birini değiştirdiğimde aşağıdaki hatayı alıyorum:

DataSet does not support System.Nullable<>.

Nasıl Null özellikleri ile bunu sınıfımda/alanlar miyim?

CEVAP
31 Mart 2009, Salı


O zaman muhtemelen null olmayan forma onları kaldırın, Nullable.GetUnderlyingType kullanarak ve belki de 7 *...* null birkaç değerleri değiştirmeniz gereklidir

Atama olacak şekilde değiştirin:

row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

ve bu sütunlar olmak eklerken:

table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
            prop.PropertyType) ?? prop.PropertyType);

Ve işe yarıyor. (?? boş birleşiyor operatörü; eğer boş olmayan, ikinci işlenen başka değerlendirilir ve kullanılır) ise ilk terim kullanır

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • AllYourNewsByMe

    AllYourNewsB

    18 Temmuz 2011
  • Trulia

    Trulia

    29 Kasım 2006
  • WHZGUD2

    WHZGUD2

    21 EYLÜL 2011