Udostępnij za pośrednictwem


Using WCF Data Services 5.6.0 with Entity Framework 6+

And now for some exciting news: you can finally use WCF Data Services with Entity Framework 6+! Today we are uploading 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+. We were able to build this provider as an out-of-band provider (that is, a provider that ships apart from the core WCF DS stack) because of the public provider work we did recently.

Upgrading an existing OData service to EF 6

If you are upgrading an existing OData service to Entity Framework 6 or greater, you will need to do a couple of things:

  1. 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.
  2. Replace the base type of your DataService. For EF 5 or below, your data service should inherit from DataService<T> where T is a DbContext or ObjectContext. For EF 6 or greater, your data service should inherit from EntityFrameworkDataService<T> where T is a DbContext. See What’s the difference between DataService and EntityFrameworkDataService below for more details.

Creating a new OData service with EF 6

If you are creating a new OData service and would like to use Entity Framework 6 or greater, you will need to follow similar steps:

  1. Create your new project. I typically use an ASP.NET Empty Web Application for this, but you can use whatever you want. Note that if you do use the empty template, you may need to create an App_Data folder for Entity Framework to work properly with LocalDB.
  2. 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.
  3. Add a new WCF Data Service. It’s best if you ensure that your tooling is up-to-date as we occasionally fix bugs in the item template. Our latest tooling installer was released with WCF DS 5.6.0. It can be downloaded here.
  4. Replace the base type of the DataService that was generated by the item template. For EF 6 or greater, your data service should inherit from EntityFrameworkDataService<T> where T is a DbContext. See What’s the difference between DataService and EntityFrameworkDataService below for more details.

What’s the difference between DataService<T> and EntityFrameworkDataService<T>?

Historically the WCF DS stack required all WCF DS-based OData services to inherit from DataService<T>. Internally, the data service would determine whether the service should use the in-box EF provider, the in-box Reflection provider, or a custom provider. When we added support for EF 6, we utilized the new public provider functionality to allow the provider to ship separately. This will allow us, for instance, to use WCF DS 5.6.0 with either EF 5, 6, or some future version. However, the new public provider functionality comes with a little bit of code you need to write. Since that code should be the same for every default EF 6 WCF DS provider, we went ahead and included a class that does this for you. EntityFrameworkDataService<T> inherits from DataService<T> and implements all the code you would need to implement otherwise. By shipping this additional class, we literally made the upgrade process as simple as changing the base type of your service.

Feedback please

We are heads down on getting our stacks updated to support OData v4, so we’ve had very limited resources to focus on testing this provider. We have a few automated tests and have tried a number of ad-hoc tests. That said, our coverage could be better so… we’re going to rely on you, our dear customer, to provide feedback of whether or not this provider works in your situation. If we don’t hear anything back, we’ll go ahead and release the provider in a week or so.

Thanks,
The OData Team

Comments

  • Anonymous
    October 03, 2013
    Good News! I've tried to "Creating a new OData service with EF 6" and faced The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. C:Users***DocumentsVisual Studio 2012ProjectsODataEF6SampleODataEF6SampleWcfDataService.svc.cs 17 18 ODataEF6Sample Anyone else facing this? What's wrong?

  • Anonymous
    October 05, 2013
    Hi   You haveany queries visit www.kbreducation.com

  • Anonymous
    October 05, 2013
    If you want to strong with .net , then follow www.kbreducation.com

  • Anonymous
    October 05, 2013
    I get this: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.resources" was correctly embedded or linked into assembly "Microsoft.OData.EntityFrameworkProvider" at compile time, or that all the satellite assemblies required are loadable and fully signed

  • Anonymous
    October 09, 2013
    I also get this error: The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Any solutions?

  • Anonymous
    October 14, 2013
    Hi , i have the same error please fix  that The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

  • Anonymous
    October 15, 2013
    Ditto on the: The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Any fixes?

  • Anonymous
    October 15, 2013
    Nevermind the alpha2 Nuget package fixes this

  • Anonymous
    October 16, 2013
    Same with this error: The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Anyone found a fix? I am yet to find any working MS WCF tutorial that works.

  • Anonymous
    October 16, 2013
    The comment has been removed

  • Anonymous
    October 17, 2013
    Hi, I have been getting the following error whilst hitting an upgraded WCF Data Service System.InvalidOperationException The resource contains value '<Complex Type Here>' which cannot be serialized. at System.Data.Services.LiteralFormatter.FormatRawLiteral(Object value) at System.Data.Services.LiteralFormatter.FormatAndEscapeLiteral(Object value) at System.Data.Services.LiteralFormatter.DefaultLiteralFormatter.FormatLiteralWithTypePrefix(Object value) at System.Data.Services.LiteralFormatter.DefaultLiteralFormatter.Format(Object value) at System.Data.Services.WebUtil.GetETagValue(Object resource, ResourceType resourceType, ICollection1 etagProperties, IDataService service, Boolean getMethod) at System.Data.Services.WebUtil.CompareAndGetETag(Object parentEntityResource, Object parentEntityToken, ResourceSetWrapper container, IDataService service, Boolean&amp; writeResponseForGetMethods) at System.Data.Services.DataService1.CompareETagAndWriteResponse(RequestDescription description, IDataService dataService, IODataResponseMessage responseMessage) at System.Data.Services.DataService1.SerializeResponseBody(RequestDescription description, IDataService dataService, IODataResponseMessage responseMessage) at System.Data.Services.DataService1.HandleNonBatchRequest(RequestDescription description) at System.Data.Services.DataService`1.HandleRequest()

  • Anonymous
    October 17, 2013
    Hi, ask a question about Edm.DateTime atom format: www.odata.org/.../atom-format default: yyyy "-" mm "-" dd "T" hh ":" mm [":" ss["." fffffff]] for example china beijing Time : 2013-10-10 08:00 , result to: 2013-10-10T00:00 what can i do , change default format, to china format? thinks a lot. my email: 18552070@qq.com I'm sorray,My English bad, chinese as follow:


你好,问一个关于WCF Data Service的Edm.DateTime序列化格式的问题, www.odata.org/.../atom-format 默认格式:yyyy "-" mm "-" dd "T" hh ":" mm [":" ss["." fffffff]] 比如 中文北京时间:2013-10-10 08:00,默认输出变成:2013-10-10T00:00 (日期和时间中间多一个T,中文时差8小时) 如何才能改成本地化的时间格式,这样显示对用户比较友好。 非常感谢! 我的邮箱:18552070@qq.com

  • Anonymous
    October 19, 2013
    The EntityFrameworkDataService<T> is not exposing properties such as CurrentDataSource of the parent DataService<T>. It has a method called CreateDataSource(). Am I missing something?

  • Anonymous
    October 20, 2013
    Please disregard my previous question (error in FormatRawLiteral).  The problem disappeared after restarting visual studio. Thanks.

  • Anonymous
    October 21, 2013
    When using the EntityFrameworkDataService, I would expect to be able to use CurrentDataSource and override CreateDataSource just as with DataService<T>. Am I missing something here? Thanks!

  • Anonymous
    October 23, 2013
    Please help me with this question: stackoverflow.com/.../wcf-data-services-5-6-entity-framework-6-0-1-code-first-with-vocabularies I'm facing a problem that Add Service Reference is not returning the properties of the fields that is generated from the edmx. For example this in the Reference.cs of the service is auto generated with WCF DataServices 5.6+EF5: <Property Name="CategoryName" Type="Edm.String" Nullable="false" MaxLength="15" FixedLength="false" Unicode="true" /> when I use EF ver 6.0.1 the service reference includes this code of the IEdmModel: <Property Name="CategoryName" Type="Edm.String" /> I need to return the full properties of the fields to the client

  • Anonymous
    October 23, 2013
    When addressing a collection of media entities, e.g.    GET ~/Employees or the media resource of a single media entity, e.g.    GET ~/Employees(1)/$value everything works fine, but when I address the media entity itself, e.g.    GET ~/Employees(1) I now get the error message "To support streaming, the data service must implement IServiceProvider.GetService() to return an implementation of IDataServiceStreamProvider or the data source must implement IDataServiceStreamProvider." IServiceProvider.GetService() is implemented and returns an implementation of IDataServiceStreamProvider, and this works in the first two cases, but in the single entity access IServiceProvider.GetService() is now no longer called for type IDataServiceStreamProvider.

  • Anonymous
    October 23, 2013
    Complex types no longer work, addressing an entity or entity set results in the error message "The resource contains value '<name of complex type>' which cannot be serialized."

  • Anonymous
    October 23, 2013
    FunctionImports no longer work: the XxxEntities.cs file gets generated with invalid code:    using System.Data.Objects;    using System.Data.Objects.DataClasses;        public virtual ObjectResult<SalesByYear_Result> SalesByYear(Nullable<System.DateTime> beginning_Date, Nullable<System.DateTime> ending_Date)        {            var beginning_DateParameter = beginning_Date.HasValue ?                new ObjectParameter("Beginning_Date", beginning_Date) :                new ObjectParameter("Beginning_Date", typeof(System.DateTime));            var ending_DateParameter = ending_Date.HasValue ?                new ObjectParameter("Ending_Date", ending_Date) :                new ObjectParameter("Ending_Date", typeof(System.DateTime));            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SalesByYear_Result>("SalesByYear", beginning_DateParameter, ending_DateParameter);        } Neither the two namespaces nor the used types ObjectResult and ObjectParameter exist.

  • Anonymous
    October 24, 2013
    Has anyone had an issue with the $expand using this update?  Seems to not work for me.  I have posted a question to Stack Overflow here: stackoverflow.com/.../ef-6-wcf-data-services-5-6-odata-expand-not-working

  • Anonymous
    October 28, 2013
    Using the Alpha 2 release from NuGet, I am able to compile the service, but when accessing it I receive the following exception: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.resources" was correctly embedded or linked into assembly "Microsoft.OData.EntityFrameworkProvider" at compile time, or that all the satellite assemblies required are loadable and fully signed. Is anyone else having issues loading resources for the Alpha 2 release?  FWIW, my /bin/lc/ folders (e.g., /bin/ja/) contain the v5.6.0 versions of Microsoft.Data.Services.resources.dll, which I would assume the EntityFrameworkProvider utilizes.

  • Anonymous
    October 29, 2013
    Unless I’m missing something, this release manages to completely omit all Referential Constraints from the metadata of any Code First EF model.  ( I haven’t tried a Database first model yet).   The spec is pretty clear that these should be supported www.odata.org/.../common-schema-definition-language-csdl and they were in the previous WCF Data Services release for Entity Framework 5.  But now they seem to be gone and the fact is not mentioned anywhere.   Am I missing something?

  • Anonymous
    October 30, 2013
    @Jeremy Caney Same here, am using alpha2, using System.Data.Services.Providers; public class SomeDataService : EntityFrameworkDataService<SomeDBEntities> get a runtime error: The server encountered an error processing the request. The exception message is 'Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.resources" was correctly embedded or linked into assembly "Microsoft.OData.EntityFrameworkProvider" at compile time, or that all the satellite assemblies required are loadable and fully signed.'. See server logs for more details.

  • Anonymous
    October 31, 2013
    I am also getting the error: The server encountered an error processing the request. The exception message is 'Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.resources" was correctly embedded or linked into assembly "Microsoft.OData.EntityFrameworkProvider" at compile time, or that all the satellite assemblies required are loadable and fully signed.' I am using the package 1.0.0-alpha2.

  • Anonymous
    October 31, 2013
    RESOLVED I resolved the error... The server encountered an error processing the request. The exception message is 'Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.resources" was correctly embedded or linked into assembly "Microsoft.OData.EntityFrameworkProvider" at compile time, or that all the satellite assemblies required are loadable and fully signed.' by removing enums from my data model.  It seems OData does not support enum types and supplies us with this unfortunately misleading exception when you include them.

  • Anonymous
    November 01, 2013
    Need Geography and Geometry support Entity Framework in OData Service using SQL Server, or some features to be able use SQL Geography.  

  • Anonymous
    November 01, 2013
    John C: Wow, great catch!  Indeed, a very bizarre error message to throw.  I wonder if it's throwing an exception when trying to lookup a localized resource for that error.  Regardless, an unfortunate limitation; I'm fond of my enums, although I suppose it's easy enough to replace them with a lookup table whose values correspond to the enum values.  Not quite as elegant of syntax due to the need to cast enums as integers, but a perfectly acceptable compromise to get Data Services working with Entity Framework 6.0.  Thanks for digging into that, and for reporting back on your find.

  • Anonymous
    November 05, 2013
    The resource error is actually a second error. It seems the Entity Framework provider DLL is missing the string resources (resx file I'm guessing) for error messages. So actually you see an error trying to get an error message string! You have to look at the stack trace to see what error message it was trying to get and then go look it up in the resources for the parent Microsoft.Data.Services (server) DLL. In my case, it was "DataService_CannotPerformOperationWithoutETag", something to do with concurrency that wasn't an issue when using EF5. It only occurred on PATCH (update) requests, though (and possibly inserts, didn't attempt those) even though reading data seemed to work okay. We've since reverted back to EF5 until things smooth out.

  • Anonymous
    November 06, 2013
    It seems that complex types no longer works with this provider. I have an entity with a complex type and everything is working fine with EF5 and Data Service 5.6, but as soon as I migrate to EF6 and use the new provider I have the following error when I try to do a query : The resource contains value '<fullname of the complex type>' which cannot be serialized. If I remove the complex type the issue disappear and everything seems to work fine. To be sure it wasn't an issue with my EDMX or my model, I have created from scratch a small, single entity, EDMX and I have exactly the same issue as soon as I start using complex types.

  • Anonymous
    November 17, 2013
    I have the same problem like Chris. The required reference to the assembly "Microsoft.OData.Service, Version=5.6.0.0" is missing! Where can i find this assembly?

  • Anonymous
    November 19, 2013
    After updating.. I'm trying to add a new Service Operation to my Service and when I try to access my resource via CurrentDataSource.MyResource...   MyResource is no longer available.  Has this functionality chanced with the update?  How do I get access to MyResource from within my new Service Operation?

  • Anonymous
    November 20, 2013
    Function Imports are now located "above" CurrentDataSource...   Instead of:      this.CurrentDataSource.MyProc(), use:                this.MyProc()

  • Anonymous
    November 20, 2013
    Never mind the last post....garbage!

  • Anonymous
    November 22, 2013
    I first installed the alpha 1 and received the error message that many on here have: Error      16           The type 'Microsoft.OData.Service.DataService`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.OData.Service, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.     C:Realtime SourceRTR 6.xRTRServicesRTRWCFDataServiceRTRWCFDataServiceRTRWCFData.svc.cs                21           16           RTRWCFDataService I then read further to a post saying to install : Install-Package Microsoft.OData.EntityFrameworkProvider -Pre  and this will install alpha2.  When I do this my package manger has two errors : Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load type 'System.Data.Entity.ConnectionFactoryConfig.InitializeEntityFrameworkCommand' from assembly 'E ntityFramework.PowerShell, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'." At C:Realtime SourceRTR 6.xRTRServicesRTRWCFDataServicepackagesEntityFramework.6.0.1toolsEntityFramework.psm1:698 char:31

  •     $domain.CreateInstanceFrom <<<< (    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException    + FullyQualifiedErrorId : DotNetMethodException Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load type 'System.Data.Entity.ConnectionFactoryConfig.AddProviderCommand' from assembly 'EntityFramework .PowerShell, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'." At C:Realtime SourceRTR 6.xRTRServicesRTRWCFDataServicepackagesEntityFramework.6.0.1toolsEntityFramework.psm1:698 char:31
  •     $domain.CreateInstanceFrom <<<< (    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException    + FullyQualifiedErrorId : DotNetMethodException And I am no longer to access the Microsoft.OData namespace that I need to get the Provider EntityFrameworkDataService.  Any help at all would be greatly appreciated.
  • Anonymous
    December 05, 2013
    The solution for me is that I had an enum usage inside my model...removing it make the error go away....hope this help !

  • Anonymous
    December 09, 2013
    I am stymied by the TypeMismatchRelationshipConstraint validation error referenced by @Alberto Silva in comments to the 5.5.0. The error was introduced in 5.4.0.  The error goes away with EF 6 but the new framework provider does not give me a viable upgrade path because of breaking changes. The lack of continuity is astonishing.

  • Anonymous
    December 10, 2013
    The comment has been removed

  • Anonymous
    December 10, 2013
    This solution works as explained with EF 6. But it seems that the provider has a problem wrapping/escaping "{" and "}" when querying for entities. E.g. (from x in [entity] where x.Name == "{" select x) would fail. NB: We did not have this problem with EF 5.5 (bacause we did not have to use the WCF Data Services Entity Framework Provider) Any fixes?

  • Anonymous
    December 12, 2013
    Do you plan on getting CurrentDataSource to work again . It useless for me with out it. I sure most of us will need to access the dbContext at some point for non trivial apps

  • Anonymous
    December 16, 2013
    CurrentDataSource no longer used to retrieve DBContext. Anyone idea about to retrieve DBContext' methods and properties?

  • Anonymous
    December 17, 2013
    What I did to get around the CurrentDataSource problem was to override CreateDataSource to be this: protected override EntityFrameworkDataServiceProvider2<UCSEntities> CreateDataSource() {    this._dataContext = new MyEntityDataSource();    return new EntityFrameworkDataServiceProvider2<UCSEntities>(        new DataServiceProviderArgs(this, this._dataContext, null, false)); } Then add a new property for your data source like this: public MyEntityDataSource CurrentDataSource {    get { return this._dataContext; } } This seems to work for me but I am having other issues. I think I'm going to have to revert back to a previous version of my project that doesn't use EF6, there are still too many issues.

  • Anonymous
    December 23, 2013
    Hi Astoria Team, Any comments on the issues experienced so far? You asked for feedback, you got it. When can we expect a beta release? It's very difficult to do any product planning if we don't know when the stack we want to use will be released as production ready.

  • Anonymous
    December 24, 2013
    Is IODataRequestMessage documenting? I need to replaced the stream to compress request stream, but i don't know what to do!

  • Anonymous
    December 30, 2013
    The comment has been removed

  • Anonymous
    January 04, 2014
    Great news, thanks

  • Anonymous
    January 05, 2014
    As an alternative to Chris Pomerantz's solution, if you don't want to override CreateDataSource then the CurrentDataSource can also be retrieved via reflection.  Details of my solution (effective for the alpha 2 version of the provider) are at stackoverflow.com/.../20896926

  • Anonymous
    January 17, 2014
    OK, slightly off topic. I've got the 5.6 Data Services nicely exposing my EF6 objects via WCF and it works well, however how do I make the service call asynchronous? Is there an easy way using the new Async and Await keywords or do I need to create callback functions etc... None of my Data Service objects have any Async methods - is there a way to get these created when referencing the service?

  • Anonymous
    January 28, 2014
    I'd like to second Adrian Hope-Bailie's question.  This is also my preferred stack for a product my company is working on, but I'm unwilling to commit to a library that is in alpha and not (apparently) being actively maintained.  Is there a roadmap or ETA for future versions of this provider?  Or is WCF Web Services no longer a priority?

  • Anonymous
    February 10, 2014
    Hi, I want to make a veru simple test of that, but It doesn'et works for me. I have VS2013 .net 4.5 EF 6.0. DataService 5.6.0. My project is Webfroms + MVC + NetAPI. I have had package : Install-Package Microsoft.OData.EntityFrameworkProvider -Pre  (it's 1.0.0-alpha2) I add a simple test.svc derived like this : public class TOTO1 : EntityFrameworkDataService<TOTOEntities> But when i use url : http://localhost:61542/TOTO1.svc/ , it never goes into InitializeService and say something like: Server as encountered an error while treating demand, see server logs files .... It seems do not like TOTO1.svc.... What's wrong.

  • Anonymous
    February 10, 2014
    To complete my previous post, John C propose to remove enum, but I've no enums in my very small sample model... So I don't know what to do..

  • Anonymous
    February 13, 2014
    Guys, I'm tearing my hair out over something that I'm sure is just a simple version mismatch.  After editing my service to add EntityFrameworkDataService like this: public class ProductsWcfDataService : EntityFrameworkDataService<AdventureWorksLT2012_AzureEntities> VS2013 is giving me the error, "Error 2 The type or namespace name 'EntityFrameworkDataService' could not be found (are you missing a using directive or an assembly reference?)" I checked my references, and I'm using the following: C:UsersMyDirdocumentsvisual studio2013ProjectsAdventureWorksLTWindowsAzurepackagesEntityFramework.6.1.0-beta1libnet45EntityFramework.dll (failed with the pre-beta version also) C:UsersMyDirdocumentsvisual studio 2013ProjectsAdventureWorksLTWindowsAzurepackagesMicrosoft.Data.Edm.5.6.0libnet40Microsoft.Data.Edm.dll C:UsersMyDirdocumentsvisual studio 2013ProjectsAdventureWorksLTWindowsAzurepackagesMicrosoft.Data.OData.5.6.0libnet40Microsoft.Data.OData.dll C:UsersMyDirdocumentsvisual studio 2013ProjectsAdventureWorksLTWindowsAzurepackagesMicrosoft.Data.Services.5.6.0libnet40Microsoft.Data.Services.dll C:Program FilesMicrosoft WCF Data Services5.6bin.NETFrameworkMicrosoft.Data.Services.Client.dll Am I missing a reference?  Or do I have a bad version somewhere?  I'm not sure why some of these references are pointing to .NET 40 versions (all updates were made by NuGet) as I have specified 4.5 in the project properties Target framework, but I don't know if that would have any effect anyway. Thanks in advance for any help.