How do I add a OData key value to my Entity Framework class?

asp.net-mvc c# entity-framework odata

Question

I'm using Entity Framework 6, Microsoft OData 2.1, and MVC 5. I'm attempting to use an EntitySetController class-written OData feed that I created. My resource is visible when I add the service reference and it uses the OData information, but when I try to save it, I have a problem:

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

This is how my OData Metadata appear:

<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 attempted to use the following code to add the [Key] attribute to the vApplication class:

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

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

But the issue still exists and my metadata remains unchanged. The EDMX model's entity key is set to ApplicationId. The metadata also don't appear to be impacted by that. How can I use a service reference in C# to consume the metadata to create a schema with an entity key?

P.S. I'm watching a movie. When I directly consume a table, it appears to function. How then do I make this compatible with Views?

1
5
4/18/2014 8:46:10 PM

Accepted Answer

ZZZ_tmp
13
4/23/2014 12:55:12 AM

Popular Answer

Would you kindly try the following:

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

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

}

Make a new Guid initialized in the constructor.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow