实体框架 - 按名称获取实体 [英] Entity framework - get entity by name

查看:93
本文介绍了实体框架 - 按名称获取实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code(例如)

I have the following code (example)

public dynamic GetData(string name) 
{
    using(var ctx = GetObjectContext()) 
    {
        switch (name) 
        {
        case "entity1":
            return ctx.entity1.ToList();
        case "entity2:
            return ctx.entity2.ToList();
        ......
        default:
            return null;
        }
    }
}

我想避免这种样品中切换。我如何可以通过名字找到需要的实体CLAS,调用了ToList()方法并返回数据?我能做到这一点使用反射?你能帮助我吗?

I want to avoid switch in this sample. How can I find needed entity clas by name, call ToList() method and return data? Can I do this using reflection? Can you help me?

推荐答案

您使用反射可以做到这一点,但你还需要使用泛型,因为列表类型的了ToList()方法返回是每一个实体类型不同

You can do it using reflection, however you will also need to use generics because the type of list returned by the ToList() method is different for each entity type.

您可以通过反射访问属性的getter像这样:

You can access a property getter through reflection like so:

var enumerable = typeof([ClassNameOfContext]).GetProperty(name).GetValue(ctx, null);

[ClassNameOfContext] 是CTX是一个实例类的名称。这不是从你的code显而易见的,但你知道它: - )

Whereas [ClassNameOfContext] is the name of the class that ctx is an instance of. This is not obvious from your code, but you know it :-)

问题是,枚举将是对象,并已被强制转换为 IEnumerable的<&的EntityType GT; ,其中的EntityType 是实体的,你正在访问类型。换句话说,这取决于你正在传递的名字。如果您使用泛型确定类型,您将能够正确地投对象,并没有返回动态甚至

The problem is that enumerable will be an object and has to be casted to IEnumerable<EntityType> where EntityType is the type of entity you are accessing. In other words, it depends on the name you are passing. If you use generics to determine the type, you will be able to properly cast the object and don't have to return a dynamic even.

public TEntity Get<TEntity>(string name)
{
    ...

和上面改造行:

var enumerable = (IEnumerable<TEntity>)(typeof([ClassNameOfContext]).GetProperty(name).GetValue(ctx, null));
return enumerable.ToList();

在这里你去!

附录:你可以,可以想象,摆脱字符串参数,太 - 在字符串中具有类型或属性名称应尽量避免使用,因为它不是类型安全的。编译器不能识别它,和IDE功能如重构不占它。这里的问题是,属性名称通常是实体类型名称的多元化的形式。但是你可以使用反射来查找其类型相符的 TEntity 属性。在我离开这个作为一个练习: - )

Addendum: You could, conceivably, get rid of the string parameter, too - having names of types or properties in strings should be avoided where possible because it is not type safe. The compiler does not recognize it, and IDE features such as refactorings don't account for it. The problem here is that the property names are usually the pluralized form of the entity type names. But you could use reflection to find the property whose type matches the TEntity. I leave this as an exercise :-)

这篇关于实体框架 - 按名称获取实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆