Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DBContext to ObjectContext for use with GridView

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'.

like image 257
Myster Avatar asked Nov 09 '11 03:11

Myster


3 Answers

Try this:

var context = new YourDbContext(); var adapter = (IObjectContextAdapter)context; var objectContext = adapter.ObjectContext; 
like image 55
marianosz Avatar answered Sep 30 '22 20:09

marianosz


Try this one ->

protected void OrdersDataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)   {        var context = new YourContext();     e.Context = ((IObjectContextAdapter)context).ObjectContext; } 
like image 23
user2076170 Avatar answered Sep 30 '22 19:09

user2076170


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.

like image 26
Ali Fattahian Avatar answered Sep 30 '22 18:09

Ali Fattahian