【问题标题】:How to use the repository pattern in ASP.NET Core MVC together with Entity Framework Core?如何将 ASP.NET Core MVC 中的存储库模式与 Entity Framework Core 一起使用?
【发布时间】: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”方法中指定将使用哪个数据库(如果可能)。我的目标不是依赖特定的数据库。

我已经做了什么:

  1. 为“实体”文件夹中的模型创建了 3 个 POCO 类:

  1. 这是我定义存储库接口的方式:

     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();
     }
    
  2. 创建“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();            
         }
     }
    
  3. 为每个实体创建一个存储库:(您真的需要为 PostgreSQL 创建另一个存储库吗?)

     public class BookRepository : Repository<Entities.Book>
     {
         public BookRepository(Microsoft.EntityFrameworkCore.DbContext context) : base(context)
         {
         }
     }
    
  4. 在“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();
         }
    }

【问题讨论】:

标签: c# asp.net-core entity-framework-core repository-pattern


【解决方案1】:
  1. onfigure 方法中注册您的BookRepository,例如services.AddScoped&lt;IRepository, BookRepository&gt;()
  2. 让框架通过构造函数注入将BookRepository 实例注入您的控制器。

【讨论】:

    【解决方案2】:

    请注意,DbContext 已经是一个工作单元,DbSet 已经是一个存储库。

    除非您有充分的理由使用自己的模式实现来包装它们,否则您可以(并且在大多数情况下应该)直接使用 EF Core 提供的实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2017-05-16
      • 2017-05-15
      相关资源
      最近更新 更多