c# - 如何将 OData 键值添加到我的 Entity Framework 类?

标签 c# asp.net-mvc entity-framework odata

我正在使用 MVC 5、Microsoft OData 2.1 和 Entity Framework 6。我正在尝试使用我使用 EntitySetController 类编写的 OData 提要。当我添加服务引用并且它使用 OData 元数据时,它可以看到我的资源,但是当我尝试保存它时出现错误:

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

我的 OData 元数据如下所示:

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

我尝试使用以下代码将 [Key] 属性添加到 vApplication 类:

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

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

但这并没有改变我的元数据,错误仍然存​​在。 EDMX 模型中的实体键设置为 ApplicationId。这似乎也不会影响元数据。如何获取元数据以生成具有实体键的架构,以便我可以在 C# 中使用服务引用使用它?

附言我正在消费一个 View 。当我直接消费一张 table 时,它似乎有效。那么我如何让它与 View 一起工作呢?

最佳答案

您正在使用 ODataModelBuilder 构建模型,对吗?如果是,请试试这个:

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

关于c# - 如何将 OData 键值添加到我的 Entity Framework 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161929/

相关文章:

c# - 如何将 ASP.NET MVC ViewResult 呈现为 HTML?

.net - 为什么我的项目中同时存在 EntityFramework 和 System.Data.Entity 程序集?

c# - EF Core 多对多自连接

c# - MVVM 和 INotifyPropertyChanged 问题

c# - 动态 Action 链接

c# - 如果FirstOrDefault返回null,则返回列表中的第一项

c# - Entity Framework 代码优先与 DbUp

c# - Call is ambiguous error 使用Linq

c# - 如何在较高级别指定要使用的数据库隔离级别?

c# - 程序随机获取 System.AccessViolationException