从Entity Framework中返回一个项目 [英] Generically return an item from Entity Framework
问题描述
我正在想这样:
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.
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屋!