【发布时间】:2020-09-21 13:41:47
【问题描述】:
我创建了一个项目 ASP.NET Core 3 MVC,我需要使用 DataBase first 方法通过 Entity Framework Core 使用数据库。现在有 2 个数据库:MSSQL 和 PostgreSQL。我需要以最简单的形式实现存储库模式。我该怎么做?
两个数据库都有表:dbo.Author (public.Author)、dbo.Book (public.Book) 和 dic.BookType 以及对应的外键。应在“ConfigureServices”方法中指定将使用哪个数据库(如果可能)。我的目标不是依赖特定的数据库。
我已经做了什么:
- 为“实体”文件夹中的模型创建了 3 个 POCO 类:
-
这是我定义存储库接口的方式:
public interface IRepository<T> where T : class { Task<List<T>> GetAll(); Task<T> GetById<TId>(TId id); void Add(T entity); void Update(T entity); void Delete(T entity); Task<int> SaveChanges(); } -
创建“Repository.cs”:
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : class { private readonly DbContext _context; public Repository(DbContext context) { _context = context; } public async virtual Task<List<TEntity>> GetAll() { return await _context.Set<TEntity>().ToListAsync<TEntity>(); } public async virtual Task<TEntity> GetById<TId>(TId id) { return await _context.Set<TEntity>().FindAsync(id); } public virtual void Add(TEntity entity) { _context.Set<TEntity>().Add(entity); } public virtual void Update(TEntity entity) { _context.Update(entity); } public virtual void Delete(TEntity entity) { _context.Set<TEntity>().Remove(entity); } public async virtual Task<int> SaveChanges() { return await _context.SaveChangesAsync(); } } -
为每个实体创建一个存储库:(您真的需要为 PostgreSQL 创建另一个存储库吗?)
public class BookRepository : Repository<Entities.Book> { public BookRepository(Microsoft.EntityFrameworkCore.DbContext context) : base(context) { } } -
在“appsettings.json”中添加了 2 个连接字符串。
接下来我应该如何对 PostgreSQL 做同样的事情以及如何在控制器中使用它?
更新:
现在很清楚它是如何工作的。但是如果我有 30-40 个表(存储库),那么在 DI 中注册所有的表不是很方便。
public void ConfigureServices(IServiceCollection services)
{
/*
string connStr = Configuration.GetConnectionString("MSSQLConnection");
services.AddDbContext<Common.ApplicationContext>(options =>
options.UseSqlServer(connStr));
*/
string connStr = Configuration.GetConnectionString("PostgreSQLConnection");
services.AddDbContext<Common.ApplicationContext>(options =>
options.UseNpgsql(connStr));
services.AddControllersWithViews();
}
我添加了一个带上下文的类。我以为不同的数据库应该有自己的类,但现在清楚了。因此,我们必须使用上下文在控制器中创建所有必要的存储库:
public class HomeController : Controller
{
protected /*DbContext*/ Common.ApplicationContext _context;
public HomeController(Common.ApplicationContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var bookRepo = new Common.Repositories.BookRepository(_context);
var books = await bookRepo.GetAll();
// ...
return View();
}
}
【问题讨论】:
-
我强烈建议你阅读这个答案:stackoverflow.com/questions/50457007/…
标签: c# asp.net-core entity-framework-core repository-pattern