WCF Data Services: Expression of type 'System.Data.Entity.Core.Objects.ObjectContext' cannot be used for return type 'System.Data.Objects.ObjectContext'
If you try to create a WCF Data Service using the Visual Studio Template(see image below) with an Entity Model created using Entity Framework 6, you’ll end with an exception like the following:
Expression of type 'System.Data.Entity.Core.Objects.ObjectContext' cannot be used for return type 'System.Data.Objects.ObjectContext'
The problem is that the WCF Data Services template does not offer support for the new Entity Framework 6 classes. In EF6 the ObjectContext is completely decoupled from the .NET framework. As a result the class no longer lives in the same namespace explaining the exception above.
WCF Data Services Entity Framework Provider
This does not mean you cannot use WCF Data Services with Entity Framework 6. There is a new NuGet package called WCF Data Services Entity Framework Provider. This NuGet package bridges the gap between WCF Data Services 5.6.0 and Entity Framework 6+.
Here are the things you need to do to get this working:
- Install the WCF Data Services Entity Framework Provider NuGet package. Since this package has a dependency on WCF Data Services 5.6.0 and Entity Framework 6 or greater, some of the other NuGet packages in your project may be upgraded as well.
- Replace the base type of your DataService. For EF 5 or below, your data service should inherit from
DataService<T>
whereT
is aDbContext
orObjectContext
. For EF 6 or greater, your data service should inherit fromEntityFrameworkDataService<T>
whereT
is aDbContext
.