ASP.NET OData,将无类型/无类型实体路由到同一个控制器

时间:2016-11-28 16:34:44

标签: c# asp.net api web odata

我正在使用ASP.NET OData API 6.0版 我正在使用无类型对象创建EDM模型。 原因是我的数据库中有一个语义数据模型,任何对象类型的crud操作都是使用相同的代码完成的。所以我基本上只需要创建一个解析OData查询字符串的控制器,并将其应用于我本地加载对象的方式。我几乎都在工作。什么缺少以某种方式定义路由动态....

那么如何映射实体x,y和z以使用相同的控制器?

我构建模型的代码类似于下面的代码。这将路由到名为IdentitiesController,ResourcesController,SystemsController和OrgunitsController的控制器。但是它们都应该路由到同一个控制器“NativeObjectsController”....

下面只是一组可能的实体类型......最终用户可以创建自己的类型,所以我不能只创建专门的控制器......

public static void Register(HttpConfiguration config)
{
  IList<IODataRoutingConvention> routingConventions = ODataRoutingConventions.CreateDefault();
  IODataPathHandler pathHandler = new DefaultODataPathHandler();

  config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: "odata/dataobjects",
    model: GetEntityModel()
   // ,pathHandler: pathHandler,
    //routingConventions: routingConventions
  );

  var routes = config.Routes;
  config.AddODataQueryFilter();
  config.EnsureInitialized();
}

public static EdmModel GetEntityModel()
{
  if (model != null)
    return model;

  model = new EdmModel();
  EdmEntityContainer container = new EdmEntityContainer(ns_ois, "OISContainer");
  model.AddElement(container);

  AddDataObjectTypeToModel(model, container, "IDENTITY", "Identities");
  AddDataObjectTypeToModel(model, container, "RESOURCE", "Resources");
  AddDataObjectTypeToModel(model, container, "SYSTEM", "Systems");
  AddDataObjectTypeToModel(model, container, "ORGUNIT", "OrgUnits");

  return model;
}

private static void AddDataObjectTypeToModel(EdmModel model, EdmEntityContainer container, string dataObjectSystemName, string entitySetName)
{
  DataObjectTypeController dotController = Factory.Default.CreateController<DataObjectTypeController>();
  int dotId = dotController.GetId(dataObjectSystemName);
  DataObjectType dot = dotController.GetDataObjectType(dotId);

  var entityObject = new EdmEntityType(ns_ois, dataObjectSystemName);
  model.AddElement(entityObject);
  entityObject.AddKeys(entityObject.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
  entityObject.AddStructuralProperty("UId", EdmPrimitiveTypeKind.Guid, false);
  entityObject.AddStructuralProperty("DisplayName", EdmPrimitiveTypeKind.String, false);

  foreach (var property in dot.GetProperties())
  {
  }

  var entitySet = container.AddEntitySet(entitySetName, entityObject);
}

0 个答案:

没有答案