有没有办法在OData ASP.NET Core Web API中根据模型字符串名称动态设置实体?

huangapple go评论56阅读模式
英文:

There is a way to set entities dynamically based on model string name in odata asp net core web api?

问题

我正在尝试基于string namevariable typesodata中动态注册实体。

var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Employee>("Employees");
modelBuilder.EntitySet<Manager>("Managers");

我正在尝试寻找一种动态的方法。

英文:

I am trying to register entities dynamically in odata based on string name or variable types.

var modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet&lt;Employee&gt;(&quot;Employees&quot;);
            modelBuilder.EntitySet&lt;Manager&gt;(&quot;Managers&quot;);

I am using this way but trying to find dynamic one.

答案1

得分: 0

你可以使用反射来实现,例如使用实体名称字符串变量注册 "empolyee":

string entityName = "Employee";

在创建 ModelBuilder 后,使用以下代码来执行 modelBuilder.EntitySet<Employee>("Employees"); 使用反射:

Type entityType = Type.GetType($"EmployeeNamespace.{entityName}");
var entitySetMethod = typeof(ODataConventionModelBuilder).GetMethod("EntitySet");
var genericEntitySetMethod = entitySetMethod.MakeGenericMethod(entityType);
genericEntitySetMethod.Invoke(modelBuilder, new object[] { entityName });
英文:

You can use reflection to achieve, For example register "empolyee" with entityName string variable:

string entityName = &quot;Employee&quot;;

After create modelbuilder, use the following code to execute modelBuilder.EntitySet&lt;Employee&gt;(&quot;Employees&quot;); with Reflection.

Type entityType = Type.GetType($&quot;EmployeeNamespace.{entityName}&quot;);
var entitySetMethod = typeof(ODataConventionModelBuilder).GetMethod(&quot;EntitySet&quot;);
var genericEntitySetMethod = entitySetMethod.MakeGenericMethod(entityType);
genericEntitySetMethod.Invoke(modelBuilder, new object[] { entityName });

huangapple
  • 本文由 发表于 2023年3月9日 21:59:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定