从Entity Framework中返回一个项目 [英] Generically return an item from Entity Framework

查看:118
本文介绍了从Entity Framework中返回一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我正在想这样:

  public< GenericType?> GetObject(int id,string typeName){
switch(typeName){
caseType1:
return db.Type1s.SingleOrDefault(t => t.TypeID == id);
caseType2:
return db.Type2.SingleOrDefault(t => t.TypeID == id);
默认值:
返回null;
}
}

有可能做这样的事情吗? (我想避免的是必须先做switch语句,然后调用特定的Repository方法,因为我将不得不重复代码并执行此操作。)

解决方案

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



实体框架是否具有相当于DataContext.GetTable< TEntity>来自Linq2Sql(ObjectContext.CreateQuery< T> ;?)



有没有什么方法可以获得所有可能的类型,一个具有此TypeID属性的特定接口?如果是,那么怎么样:

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

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


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

I'm thinking something like this:

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

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> might be what you need.

Does the Entity Framework have an equivalent of DataContext.GetTable<TEntity> from Linq2Sql (ObjectContext.CreateQuery<T>?)

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

这篇关于从Entity Framework中返回一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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