How can I create dynamic builder Odata with .Net Core 2.2?

时间:2019-04-08 13:15:40

标签: asp.net-web-api asp.net-core odata

I use Odata with .NET Core.

and My Startup.cs file like above

public void ConfigureServices(IServiceCollection services)
{
    ......

    services.AddOData();
    services.AddODataQueryFilter();

    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}



public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{       
     ..............

     app.UseMvc(b =>
     {
         b.MapRoute("default", "api/{controller}/{action}");
         b.MapRoute("defaultApi", "api/{controller}/{id}");
         b.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
         b.MapODataServiceRoute("odata", null, GetEdmModel());
     });
}



private static IEdmModel GetEdmModel()
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.Namespace = "WebAPI";
    builder.ContainerName = "DefaultContainer";
    builder.EnableLowerCamelCase();
    builder.EntitySet<User>("User");
    builder.EntityType<User>()
         .Filter(Microsoft.AspNet.OData.Query.QueryOptionSetting.Allowed);
    builder.EntitySet<Camera>("Camera");
    builder.EntityType<Camera>() 
         .Filter(Microsoft.AspNet.OData.Query.QueryOptionSetting.Allowed);
    return builder.GetEdmModel();
}

I want use odata with dynamic models which are database model classes. When creating new database table, i must create builder builder.EntitySet<Camera>("Camera");

1 个答案:

答案 0 :(得分:0)

已经很晚了,但是如果有人需要,这是我的方法:

private static IEdmModel GetEdmModel()
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    var entityMethod = builder.GetType().GetMethod("EntitySet", new Type[] { typeof(string) });
    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (var assembly in assemblies)
    {
        var entityTypes = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(BaseEntity)));

        foreach (var type in entityTypes)
        {

            entityMethod.MakeGenericMethod(type)
                .Invoke(builder, new object[] { type.Name });

        }
    }
    return builder.GetEdmModel();
}