通用存储库访问数据库 [英] generic repository to access database
本文介绍了通用存储库访问数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我想创建一个通用的 Repository
类来访问数据库。它将通过类型化存储库进行扩展
public abstract class Repository< T>
类。我明白为什么,在我的背景下没有这样的收藏。我能以某种方式解决这个问题吗?
{
保护MyContext ctx = null;
$ b $ public Repository()
{
if(this.ctx == null)
{
this.ctx = new MyContext();
}
}
public T FindById(int id)
{
return this.ctx.T.Single(s => s.Id == id);
$ / code $ / pre
唯一的问题是<$ c在
this.ctx.T
中无法识别$ c> T解决方案对于Entity Framework,您可以使用 DbContext.Set 方法:
this.ctx.Set< T>()
Hi I want to create a generic
Repository
class that will access database. It will be extended by typed repositoriespublic abstract class Repository<T> { protected MyContext ctx = null; public Repository() { if (this.ctx == null) { this.ctx = new MyContext(); } } public T FindById(int id) { return this.ctx.T.Single(s => s.Id == id); } }
The only problem with this is that the
T
class is not recognized inthis.ctx.T
. I understand why, there is no such collection in my context. Can I solve this problem somehow ?解决方案For Entity Framework you can use DbContext.Set method:
this.ctx.Set<T>()
这篇关于通用存储库访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文