【问题标题】:Get entities by string in Entity Framework在实体框架中通过字符串获取实体
【发布时间】:2017-07-17 21:04:10
【问题描述】:

我正在尝试使用实体框架做一些动态代码。我有一个模型(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);

抱歉解释。

有什么想法吗?

【问题讨论】:

    标签: reflection programmatically


    【解决方案1】:

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

    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);
    

    【讨论】:

    • 我想我解释错了。我想要的是以编程方式获取我在模型中拥有的一个实体的实例。这样,我可以使用字符串来获取实体而无需编写 m.Test1....,而不是我想要类似于 m["Test1"] 的东西(不是那样,而是类似)。谢谢
    • 您可以创建实体的部分类,甚至可以通过元数据将 [required] 或其他属性放在字段上:stackoverflow.com/questions/14059455/… 这样做后,您可以使每个实体派生自 IEntity 并定义 IEntity。然后你可以做 Assembly assembly = Assembly.Load("Testy20161006");类型 t = assembly.GetType("Testy20161006.Controllers." + "Test"); IEntity 实体 = (Object)Activator.CreateInstance(t);信用约翰斯基特
    • 谢谢@kblau!我就是这样做的
    猜你喜欢
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多