当前位置: 首页 > 编程语言 > C#

在代码第一entity framework中将DbContext转换为Datatable分享

时间:2023-04-10 16:58:30 C#

C#学习教程:在CodeFirstEntityFramework中将DbContext转换为数据表我有一个继承DbContextClientTemplateModel的类。在这个类中,我有一个DbSet对象,publicvirtualDbSetImageComments{get;放;}publicvirtualDbSetImageComments{get;放;}publicvirtualDbSetImageComments{get;放;}。我正在使用代码优先实体框架。这是我的查询。使用(ClientTemplateModelcontext=newClientTemplateModel(connectionString)){varresult=context.ImageComments.Where(p=>p.Dcn==dcn).OrderByDescending(p=>p.CommentsDateTime);在这里,我想要将结果转换为DataTable。我怎样才能转换它?您可以使用扩展方法将通用列表转换为数据表,也可以使用IQueryable/Ienumerable代替IList,遵循代码DataTable表=newDataTable();foreach(PropertyDescriptorpropinproperties)table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType)??prop.PropertyType);foreach(数据中的T项){DataRowrow=table.NewRow();foreach(属性中的PropertyDescriptor道具)row[prop.Name]=prop.GetValue(item)??DBNull.Value;table.Rows.Add(行);}返回表;如果您之前没有使用过扩展方法,请参阅msdn源代码:https://stackoverflow.com/a/5805044/1018054希望这有帮助!!!以上就是C#学习教程:代码优先实体框架中DbContext转Datatable。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文来自网络收集,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: