将实体集动态添加到 ODataConventionModelBuilder 或 ODataModelBuilder

Ard*_*tak 1 odata asp.net-web-api

有没有办法将 EntitySet 动态添加到 ODataConventionModelBuilder。

我正在 .net 中开发 OData 服务。我们将返回的一些实体来自外部程序集。我很好地阅读了程序集并获取了相关类型,但由于这些类型是变量,我不确定如何将它们定义为实体集。

例子:

    public static void Register(HttpConfiguration config)
    {
        //some config house keeping here

        config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));

        //more config housekeeping
    }

    private static IEdmModel GetEdmModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.Namespace = "SomeService";
        builder.ContainerName = "DefaultContainer";

        //These are the easy, available, in-house types
        builder.EntitySet<Dog>("Dogs"); 
        builder.EntitySet<Cat>("Cats");
        builder.EntitySet<Horse>("Horses"); 

        // Schema manager gets the rest of the relevant types from reading an assembly.  I have them, now I just need to create entity sets for them

        foreach (Type t in SchemaManager.GetEntityTypes)
        {
            builder.AddEntityType(t); //Great!  but what if I want EntitySET ?
            builder.Function(t.Name).Returns<IQueryable>();  //See if you can put correct IQueryable<Type> here.

            //OR

            builder.EntitySet<t>(t.Name);  //exception due to using variable as type, even though variable IS a type

        }

        return builder.GetEdmModel();
    }
Run Code Online (Sandbox Code Playgroud)

Ard*_*tak 6

弄清楚了。只需在循环中添加这一行:

builder.AddEntitySet(t.Name, builder.AddEntityType(t));
Run Code Online (Sandbox Code Playgroud)