c# - DomainDataService (ViewModel) 通过字符串名称加载实体

标签 c# silverlight entity-framework reflection mvvm

所以我试图动态加载我的域数据服务,其中表名称是字符串...这是我到目前为止所得到的:通常我会像这样加载:

 theDomainDataService.Load(theDomainDataService.getUsersQuery());

所以我试图自动通过字符串名称加载哪个实体。

 String theVariableEntityName = "Users";
 Type t = theDomainDataService.GetType();
 MethodInfo stuff = t.GetMethod("Get" + theVariableEntityName + "Query");
 var theQuery = stuff.Invoke(theDomainDataService, null);
 theDomainDataService.Load((EntityQuery<MySite.Web.Models.User>)theQuery);
  ---------------------------------------------------------^ Problem

这实际上正确加载了我的domainDataService,但我需要的是一种动态方式来推断 EntityQuery 的类型(无需明确声明它将是一个 User),因为事实上它可以是任何东西。

我从 DomainDataService 类中尝试过此操作,但没有成功,它没有找到方法的“Set”或“Entry”。

    public List<object> void PopulateEntity(string theEntityName)
    {
        Type theEntity = Type.GetType("MySiteMaintenance.Web.Models." + theEntityName);
        using (var db = new DatingEntities()) 
        {                        
              IQueryable query = db.Set(theEntity);
              foreach (var item in query) 
              {
                  var entry = db.Entry(item);
              }
        }
    }

请记住,我需要的只是一个填充的实体(当我所拥有的只是实体的名称时)填充的客户端......所以我可以说

 DomainServiceClass theClass = new DomainServiceClass();
 theClass.Load(theClass.GetEntityNameQuery());

这样我就可以引用适当加载的实体... theClass.Entity(用户...问题等..)

最佳答案

我仍然不确定我是否遵循,但是......

我的 Sandbox 命名空间中有一个 Post 实体,我使用字符串中的实体类型名称从 DbContext 实例获取该实体与...

                // Get my entity type (if in same assembly, else you'll have to specify)
                Type postType = Type.GetType("Sandbox.Post");

                using (var db = new StackOverflowEntities()) {                        

                    // not required
                    db.Configuration.ProxyCreationEnabled = false;

                    IQueryable query = db.Set(postType);
                    foreach (var item in query) {

                        DbEntityEntry entry = db.Entry(item);

                    }
                }

这会导致基于实体类型字符串检索任何 DbSet。在项目 foreach 循环中的断点下方 - 显示值。

enter image description here

关于c# - DomainDataService (ViewModel) 通过字符串名称加载实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142504/

相关文章:

c# - 自适应卡片中的轮播

Silverlight UserControl 和他自己的 Viewmodel 托管在 View 中

silverlight - 使用 Segoe WP 字体的等宽 TextBlock

c# - Entity Framework - 一对多 - 从两个表中选择

c# - 为什么重置后旧值留在这个对象中?

c# - 忽略 Entity Framework 中的特定列?

c# - 如何在 Unity 中更改 Sprite uv?

c# - 如何将更改从模型获取到模型 View 中?

c# - 从 Host.TopLevelDomain C# 获取有效的 web url

silverlight - 如何绑定(bind)文本框的 SelectionStart 属性?