2017-07-17 129 views
0

我正在尝试使用实体框架做一些动态代码。我有一个模型(Model1)和一个表格(Test1),这很简单。我想要做的是用程序名称编程访问模型Test1,以便在不同的任务中使用它。我一直在寻找在谷歌,我发现Finding entities by key in entity framework但它不工作,或者我没有任何想法...通过实体框架中的字符串获取实体

当我运行这段代码它打破上试图设置entityProperty

Model1Container m = new Model1Container(); 
      PropertyInfo entityProperty = m.GetType().GetProperties().Where(t => t.Name == "Test1").Single(); 
      var baseQuery = (IQueryable<IIdentity>)entityProperty.GetValue(m, null); 

对不起,解释。

任何想法?

回答

0

您创建一个字符串名称的对象并设置其属性:

public class Test 
{ 
    //All my classes have these properties 
    //You can set up an interface and in the method you can set entity to an interface type 
    //You can even put these interfaces on edmx generated entities 
    //http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-data-model 
    public string AString { get; set; } 
    public DateTime ADate { get; set; } 
} 

public class HomeController : Controller 
{ 
    public ActionResult IndexStackOverflow101() 
    { 
     Assembly assembly = Assembly.Load("Testy20161006"); 
     Type t = assembly.GetType("Testy20161006.Controllers." + "Test"); 
     Object entity = (Object)Activator.CreateInstance(t); 
     PropertyInfo entityProperty = t.GetProperty("AString"); 
     PropertyInfo entityPropertyTwo = t.GetProperty("ADate"); 
     entityProperty.SetValue(entity, Convert.ChangeType("ap", entityProperty.PropertyType), null); 
     entityPropertyTwo.SetValue(entity, Convert.ChangeType(DateTime.Now, entityPropertyTwo.PropertyType), null); 
+0

我想我错了解释..我想是获得一个实体的编程实例,我在模型。这样,我可以使用字符串来获取实体,而不用写m.Test1 ....,而不是我想要类似于m [“Test1”]的东西(不是那种方式,但类似)。 Thx – kartGIS

+0

您可以创建实体的部分类,甚至通过元数据在字段上添加[必需]或其他属性:http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-数据模型一旦你这样做,你可以让每个实体从IEntity派生并定义IEntity。然后你可以做Assembly Assembly = Assembly.Load(“Testy20161006”); 类型t = assembly.GetType(“Testy20161006.Controllers。”+“Test”); IEntity entity =(Object)Activator.CreateInstance(t);信贷John Skeet – kblau

+0

Thx @kblau!我这样做了 – kartGIS