【问题标题】:How can I create dynamic builder Odata with .Net Core 2.2?如何使用 .Net Core 2.2 创建动态构建器 Odata?
【发布时间】:2019-08-29 15:47:44
【问题描述】:

我将 Odata 与 .NET Core 一起使用。

和上面的我的 Startup.cs 文件

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();
}

我想将 odata 与作为数据库模型类的动态模型一起使用。创建新数据库表时,我必须创建builder builder.EntitySet&lt;Camera&gt;("Camera");

【问题讨论】:

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


    【解决方案1】:

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2017-08-31
      相关资源
      最近更新 更多