Convert DBContext to ObjectContext for use with GridView

ぐ巨炮叔叔 提交于 2019-11-26 11:01:20

问题


I have a webforms project using EF codefirst to persist data. I\'d like to use a GridView and EntityDataSource, in order to save writing CRUD. Is this possible?

Can I convert my DBContext to an ObjectContext that is expected by the EntityDataSource?

Here\'s what I tried:

<asp:EntityDataSource ID=\"OrdersDataSource\" runat=\"server\" ContextTypeName=\"SomeNamespace.Models.ShopDBContext\" 
     EnableFlattening=\"False\" EntitySetName=\"Orders\" EntityTypeFilter=\"Order\" EnableDelete=\"False\" 
     EnableUpdate=\"False\" Include=\"OrderLines\" OrderBy=\"it.Id\"> 
</asp:EntityDataSource>

<asp:GridView ID=\"OrdersGridView\" runat=\"server\" AllowPaging=\"True\" AllowSorting=\"True\" 
     AutoGenerateColumns=\"True\" DataKeyNames=\"Id\" DataSourceID=\"OrdersDataSource\" /> 

However I get this exception:

Unable to cast object of type \'SomeNamespace.Models.ShopDBContext\' to type \'System.Data.Objects.ObjectContext\'.


回答1:


Try this:

var context = new YourDbContext();
var adapter = (IObjectContextAdapter)context;
var objectContext = adapter.ObjectContext;



回答2:


Try this one ->

protected void OrdersDataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)  
{   
    var context = new YourContext();
    e.Context = ((IObjectContextAdapter)context).ObjectContext;
}



回答3:


After 2 days of struggling , I found this link which helped me a lot.I am working withVS 2012 and I had same problem with DBContext.
According to the link, in VS2012 the default code generator was changed to generate POCO entities and DBContext as opposed to entities derived from EntityObject and ObjectContext which was default in VS2010.
In solution explorer, under your entity model, You need to remove tt templates and, in the designer, righ-click on the designer surface and then in the properties change the code generation strategy from None to Default to get EntityObject based entities and ObjectContext derived context.



来源:https://stackoverflow.com/questions/8059900/convert-dbcontext-to-objectcontext-for-use-with-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!