簡體   English   中英

在Code第一實體框架中將DbContext轉換為Datatable

[英]Convert DbContext to Datatable in Code first entity framework

您好我正在嘗試將DbContext結果轉換為DataTable 我有一個classinherits DbContext ClientTemplateModel 在這個類中,我有一個DbSet對象,即public virtual DbSet<imagecomment> ImageComments { get; set; } public virtual DbSet<imagecomment> ImageComments { get; set; } public virtual DbSet<imagecomment> ImageComments { get; set; } 我正在使用Code第一個實體框架

這是我的查詢。

using (ClientTemplateModel context = new ClientTemplateModel(connectionString))
{
  var result = context.ImageComments.Where(p => p.Dcn == dcn).OrderByDescending(p => p.CommentsDateTime);
}

在這里,我想將result轉換為DataTable 我該怎么轉換呢?

你可以使用將你的Generic List轉換為Datatable的Extension方法,也可以使用IQueryable / Ienumerable而不是IList,按照代碼

  public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties = 
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }

如果您之前沒有使用過擴展方法,請參閱msdn

來源: https//stackoverflow.com/a/5805044/1018054

希望這可以幫助 !!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM