一般从实体框架返回一个项目
我遇到过这样的情况:网站可以根据字符串从我的数据库中请求数据(不用担心 - 我正在防止 SQL 注入)。出于各种原因,我希望有一个方法可以返回用户期望的对象(从 EF)(最终通过部分页面返回)。
我在想这样的事情:
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 语句,然后调用特定的存储库方法,因为这样我就必须重复代码并多次执行此操作。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CreateQuery
可能就是您所需要的。实体框架是否具有与 DataContext 等效的功能。 GetTable来自 Linq2Sql (ObjectContext.CreateQuery?)
有没有什么方法可以获取要传入的所有可能类型,以与具有此 TypeID 属性的特定接口兼容?如果是这样,怎么样:
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:
实际上,任何类型的通用报告生成器/查询执行器/等都可能更适合直接 SQL 查询,而不是尝试将动态逻辑融入 EF 或 LINQ。
Practically speaking, any kind of generalized report generator / query executor / etc. is probably better served with direct SQL queries than trying to fit your dynamic logic into EF or LINQ.
我想手动将表达式树串在一起并不
像我想象的那么难。
How about
I guess manually stringing together an Expression tree isn't as hard as I thought it was.
考虑到当你调用这个方法时事情会是什么样子......大概它看起来像这样:
我想不出一种方法来使返回值的类型更具体,因为 EF 中的对象没有公共基类,它们也不实现公共接口。当然,您可以让他们实现这样的接口(正如 Adam 建议的那样,尽管目的不同),然后像这样重写您的方法: 然后
您的调用代码将如下所示:
当然,我对您的调用代码的猜测可能是离得很远。
Considering how things will look when you call this method...presumably it would look something like this:
I can't think of a way to make the type of the returned value more specific, because objects in the EF don't have a common base class, neither do they implement a common interface. Of course, you could make them implement such an interface (as Adam suggests, though with a different purpose), and then rewrite your method like this:
Then your calling code would look like this:
Of course, my guess at your calling code may be way off.