Question

I am using MVC 5, Microsoft OData 2.1, and Entity Framework 6. I am trying to consume an OData feed that I wrote using the EntitySetController class. when I add the service reference and it consumes the OData metadata, it can see my resource, but when I try to save it I get an error:

The custom tool 'DataServicesCoreClientGenerator' failed. Data service client code-generation failed: Schema specified is not valid. Errors: (0,0) : error 0159: Entity '...' has no key defined. Define the key for this EntityType..#

My OData Metadata looks like this:

<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
   <edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0">
       <Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="WcfResearch.Entities">
         <EntityType Name="vApplication">
           <Property Name="ApplicationName" Type="Edm.String"/>
           <Property Name="LoweredApplicationName" Type="Edm.String"/>
           <Property Name="ApplicationId" Type="Edm.Guid" Nullable="false"/>
           <Property Name="Description" Type="Edm.String"/>
         </EntityType>
       </Schema>
       <Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="Default">
          <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
              <EntitySet Name="Applications" EntityType="WcfResearch.Entities.vApplication"/>
          </EntityContainer>
       </Schema>
  </edmx:DataServices>
</edmx:Edmx>

I tried to add the [Key] attribute to the vApplication class with the following code:

[MetadataType(typeof(vApplicationKey))]
public partial class vApplication
{
}

public class vApplicationKey
{
    [Key]
    public System.Guid ApplicationId { get; set; }
}

But that does not change my metadata and the error persists. The entity key in the EDMX model is set to ApplicationId. That also does not seem to affect the metadata. How do I get the metadata to generate a schema with an entity key so that I can consume it in C# with a service reference?

P.S. I am consuming a view. It seems to work when I directly consume a table. So how do I get this to work with Views?

Was it helpful?

Solution

You are using ODataModelBuilder to build the model, right? if yes, please try this:

EntityType _vApplicationKey=oDataModelBuilder.Entity<vApplicationKey>()
_vApplicationKey.HasKey(a => a.ApplicationId);

OTHER TIPS

could you please try to do this:

public class vApplicationKey
{
   public vApplicationKey
   {
     ApplicationId = System.Guid.NewGuid();
   }

 [Key]
 public System.Guid ApplicationId { get; set; }

}

Initialise a new Guid in the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top