How to prevent ODataConventionModelBuilder to automatically expose all derived types' metadata?

南楼画角 提交于 2019-12-01 00:29:08

问题


I'm using ODataConventionModelBuilder to build Edm Model for Web API OData Service like this:

ODataModelBuilder builder = new ODataConventionModelBuilder();

builder.Namespace = "X";

builder.ContainerName = "Y";

builder.EntitySet<Z>("Z");

IEdmModel edmModel = builder.GetEdmModel();

Class Z is located in one assembly, and there is public class Q derived from Z located in different assembly.

The ODataConventionModelBuilder will generates Edm Model that includes definition of class Q (among other derived classes) and it will be exposed with service metadata. That is undesirable in our case.

When derived class in inaccessible (e.g. defined as internal) such problem, sure, doesn't exist.

Is there way to force the ODataConventionModelBuilder to do NOT automatically expose all derived types' metadata?


回答1:


This should work:

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

builder.Namespace = "X";

builder.ContainerName = "Y";

builder.EntitySet("Z");

builder.Ignore<Q>();

IEdmModel edmModel = builder.GetEdmModel();



回答2:


There is no way of disabling the automatic discovery and this is by design. See here.

However, there's a workaround. You have to explicitly Ignore each derived type and then proceed on manually mapping each derived type. Here's a nice loop to ignore the derived types:

var builder = new ODataConventionModelBuilder();
builder.Namespace = "X";
builder.ContainerName = "Y";
builder.EntitySet<Z>("Z");

var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.IsSubclassOf(typeof(Z)));

foreach (var type in types)
    builder.Ignore(types.ToArray());

//additional mapping of derived types if needed here

var edmModel = builder.GetEdmModel();

See my blog post for more details.



来源:https://stackoverflow.com/questions/26257993/how-to-prevent-odataconventionmodelbuilder-to-automatically-expose-all-derived-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!