简体   繁体   English

OData v4 EDM模型-单独的配置类?

[英]OData v4 EDM model - separate configuration classes?

I'd like to use OData 4 along with WebApi2 and EF, where as for the latter I got about 30 model configuration classes. 我想将OData 4与WebApi2和EF一起使用,至于后者,我获得了大约30个模型配置类。 Now, since OData requires an EDM model, I would like to somehow reuse my existing model configuration - or at least put the configuration classes into a different library to keep my web api configuration manageable. 现在,由于OData需要EDM模型,因此我想以某种方式重用我现有的模型配置-或至少将配置类放入其他库中,以使Web api配置易于管理。

I tried creating EDM entity type configuration classes using EntitySetConfiguration<'1> , however the constructor of that class is internal. 我尝试使用EntitySetConfiguration<'1>创建EDM实体类型配置类,但是该类的构造函数是内部的。 So - is there a way to automatically build an EDM model using a DbContext during runtime or create separate configuration classes? 那么-有没有办法在运行时使用DbContext自动构建EDM模型或创建单独的配置类?

You can build an edm model using a DBContext via reflection. 您可以使用DBContext通过反射来构建edm模型。

public static void Register(HttpConfiguration config)
{
    var modelBuilder = new ODataConventionModelBuilder();
    modelBuilder.ContainerName = "EntityContainer";

    using(var ctx = new MyDBContext()) 
    {
        var dbSets = ctx.GetType().GetProperties();
        foreach(var set in dbSets)
        {
            if(set.PropertyType.IsGenericType)
            {
                 method = entitySet.MakeGenericMethod(set.PropertyType.GenericTypeArguments[0]);
                 bool containsEntity = false;
                 foreach (var entity in modelBuilder.EntitySets)
                 {
                     if (entity.GetType().Equals(set.PropertyType.GenericTypeArguments[0]))
                         containsEntity = true;


                     if (!containsEntity)
                         method.Invoke(modelBuilder, new[] { set.Name });
                  } 
             }
         }
     }
     _config.MapODataServiceRoute(
           routeName: "entities",
           routePrefix: API_ENTITIES_BASE_URI,
           model: modelBuilder.GetEdmModel()
           );
}

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM