0

我正在尝试使用实体框架做一些动态代码。我有一个模型(Model1)和一个表(Test1),很简单。我想要做的是使用表的名称以编程方式访问模型 Test1,以便在不同的任务中使用它。我在谷歌中寻找,我发现在实体框架中按键查找实体,但它不起作用,或者我不知道......

当我运行此代码时,它会在尝试设置 entityProperty 时中断

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

对不起,解释。

有任何想法吗?

4

1 回答 1

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);
于 2017-07-17T23:34:00.693 回答