Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

c# - Convert DbContext to Datatable in Code first entity framework

Hello I am trying to convert DbContext result to DataTable. I have one class i.e. ClientTemplateModel which inherits DbContext. In this class I have one DbSet object i.e. public virtual DbSet<imagecomment> ImageComments { get; set; }. I am using Code first entity framework.

Here is my query.

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

Here I am want convert the result into DataTable. How can I convert this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use Extension method that converts your Generic List To Datatable , you can use IQueryable/Ienumerable also instead of IList , follow the code

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

if you have not used extension method before please see msdn

source : https://stackoverflow.com/a/5805044/1018054

Hope this helps !!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...