是否可以为单个实体类型提供多个控制器?

时间:2015-08-05 11:56:22

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

我有一个实体框架模型。让我们说我们有一个对象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错误消息:

  

无法自动绑定导航属性&#39; FooThing&#39;实体类型&#39; Foo&#39;对于实体集或单身&#39; Bars&#39;因为有两个或多个匹配的目标实体集或单例。匹配的实体集或单身人士是:傻瓜,足球。

我有点理解这个问题,但是如果我知道只有足球会有禁区的事实,我有办法帮助系统了解禁区只会有足球吗?

1 个答案:

答案 0 :(得分:4)

The answer is absolutely yes. There are many fluent APIs that you can call to set the binding manually, then to suppress the convention binding. For example:

HasManyBinding
HasRequiredBinding
HasOptionalBinding
HasSingletonBinding
...

Based on your information, you can call the following to make the binding manually:

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

I also create a simple Foo and Bar class model to test. The below result shows the metadata:

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

As you can see, "HasRequiredBinding" can make the navigation property as non-nullable, while, "HasOptionBinding" can make it nullable.

Hope it can help. Thanks.

相关问题