英文:
There is a way to set entities dynamically based on model string name in odata asp net core web api?
问题
我正在尝试基于string name
或variable types
在odata
中动态注册实体。
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<Employee>("Employees");
modelBuilder.EntitySet<Manager>("Managers");
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 = "Employee";
After create modelbuilder, use the following code to execute modelBuilder.EntitySet<Employee>("Employees");
with Reflection.
Type entityType = Type.GetType($"EmployeeNamespace.{entityName}");
var entitySetMethod = typeof(ODataConventionModelBuilder).GetMethod("EntitySet");
var genericEntitySetMethod = entitySetMethod.MakeGenericMethod(entityType);
genericEntitySetMethod.Invoke(modelBuilder, new object[] { entityName });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论