一般返回来自实体框架项目 [英] Generically return an item from Entity Framework

查看:159
本文介绍了一般返回来自实体框架项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,网站可以从数据库中请求数据基于字符串(不要担心 - 我防范SQL注入)。由于各种原因,我想有一个方法返回用户期望的对象(从EF返回)(它最终通过部分页面返回)。

I have a situation where a website can ask for data from my database based on a string (don't worry - I'm protecting against SQL injections). For various reasons, I would like to have a single method which returns back the object (from EF) that the user expects (which, ultimately, comes back through a partial page).

我在这样想:

public <GenericType?> GetObject(int id, string typeName) {
  switch(typeName) {
    case "Type1":
      return db.Type1s.SingleOrDefault(t => t.TypeID == id);
    case "Type2":
      return db.Type2.SingleOrDefault(t => t.TypeID == id);
    default:
      return null;
  }
}

可以这样做吗? (我想避免的是先做switch语句,然后调用特定的Repository方法,因为我将不得不重复代码,这样做了很多次。)

Is it possible to do something like this? (What I am trying to avoid is having to do the switch statement earlier and then call the specific Repository method because I would then have to repeat code and do this a number of times.)

推荐答案

CreateQuery< T> 可能是您需要的。

实体框架是否具有相当于DataContext.GetTable从Linq2Sql(ObjectContext.CreateQuery?)

有什么办法你可以得到所有可能的类型,你会传递来comport一个具有此TypeID属性的特定接口?如果是,如何:

Is there any way you can get all the possible types you'd be passing in to comport with a particular interface that has this TypeID property on it? If so, how about:

    public T GetResult<T>(int id, string typeName) where T : IClassWithTypeID {
        YourEntities db = new YourEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeName));

        return result.Single(t => t.TypeID == id);
    }

这篇关于一般返回来自实体框架项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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