c# - 单个实体类型是否可以有多个 Controller ?

标签 c# entity-framework asp.net-web-api odata

我有一个 Entity Framework 模型。假设我们有一个对象 Foo 和一个对象 Bar。它们是相关的,因此 Foo 具有到 Bar 的导航属性,反之亦然。

现在,对于我的 OData 端点,我希望有两个可用于 Foo 的集合,例如这样声明:

var builder = new ODataConventionModelBuilder { Namespace = "Test" };
builder.EntitySet<Foo>("Fools");
builder.EntitySet<Foo>("Footballs");
builder.EntitySet<Bar>("Bars");

这里的想法是,对 Fools 的访问将通过 FoolsController 进行,而对 Footballs 的访问将通过 FootballsController 进行,这样我就可以在每个端点。

但是,尝试执行此操作会导致出现以下 NotSupportedException 错误消息:

Cannot automatically bind the navigation property 'FooThing' on entity type 'Foo' for the entity set or singleton 'Bars' because there are two or more matching target entity sets or singletons. The matching entity sets or singletons are: Fools, Footballs.

我有点理解这个问题,但如果我知道只有足球才会有酒吧,有没有办法帮助系统了解酒吧只会有足球?

最佳答案

答案是肯定的。 您可以调用许多流畅的 API 来手动设置绑定(bind),然后抑制约定绑定(bind)。例如:

HasManyBinding
HasRequiredBinding
HasOptionalBinding
HasSingletonBinding
...

根据您的信息,您可以调用以下方法手动进行绑定(bind):

builder.EntitySet<Bar>("Bars").HasRequiredBinding(b => b.FooThing, "Fools");

我还创建了一个简单的 Foo 和 Bar 类模型来测试。下面的结果显示了元数据:

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
  <edmx:DataServices>
    <Schema Namespace="WebApiTest" xmlns="http://docs.oasis-open.org/odata/ns/ed
m">
      <EntityType Name="Foo">
        <Key>
          <PropertyRef Name="Id" />
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false" />
      </EntityType>
      <EntityType Name="Bar">
        <Key>
          <PropertyRef Name="Id" />
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false" />
        <NavigationProperty Name="FooThing" Type="WebApiTest.Foo" Nullable="fals
e" />
      </EntityType>
    </Schema>
    <Schema Namespace="Test" xmlns="http://docs.oasis-open.org/odata/ns/edm">
      <EntityContainer Name="Container">
        <EntitySet Name="Fools" EntityType="WebApiTest.Foo" />
        <EntitySet Name="Footballs" EntityType="WebApiTest.Foo" />
        <EntitySet Name="Bars" EntityType="WebApiTest.Bar">
          <NavigationPropertyBinding Path="FooThing" Target="Fools" />
        </EntitySet>
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>

如您所见,“HasRequiredBinding”可以使导航属性不可为空,而“HasOptionBinding”可以使其可以为空。

希望能帮到你。谢谢。

关于c# - 单个实体类型是否可以有多个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31831843/

相关文章:

c# - 在 ASP.NET Web Config 中加密连接字符串

c# - WCF selfhost 所需的组件?

c# - 为什么嵌套 if 语句可以工作,但 "&&"运算符却不能? (字母计数脚本)

entity-framework - "Metadata information not found"使用 EF4 的 POCO 模板时?

asp.net-mvc - 在ASP.NET MVC中管理ADO.NET Entity Framework ObjectContext

c# - MVC中的属性和过滤器有什么区别

c# - 不使用 Task.Result 的异步/等待死锁

c# - 如何使用 LINQ 使用字典填充类

c# - 如何获得进程所有者的用户名?

c# - Entity Framework 在哪里存储属性名称和它在 SQL 中选择的列之间的映射?