Myster
Myster

Reputation: 18096

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

Upvotes: 29

Views: 32804

Answers (3)

Ali Fattahian
Ali Fattahian

Reputation: 495

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.

Upvotes: 2

user2076170
user2076170

Reputation: 41

Try this one ->

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

Upvotes: 4

marianosz
marianosz

Reputation: 1234

Try this:

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

Upvotes: 74

Related Questions