簡體   English   中英

如何將 ASP.NET Core MVC 中的存儲庫模式與 Entity Framework Core 一起使用?

[英]How to use the repository pattern in ASP.NET Core MVC together with Entity Framework Core?

我創建了一個項目 ASP.NET Core 3 MVC,我需要使用數據庫優先方法通過 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 執行相同操作以及如何在 controller 中使用它?

更新:

現在很清楚它是如何工作的。 但是如果我有30-40個表(repositories),那么把它們全部注冊到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();
    }

我添加了一個帶有上下文的 class。 原以為不同的數據庫應該有自己的class,現在清楚了。 因此,我們必須使用上下文在 controller 中創建所有必要的存儲庫:

    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();
         }
    }
  1. services.AddScoped<IRepository, BookRepository>()類的onfigure方法中注冊您的BookRepository
  2. 讓框架通過構造函數注入將BookRepository實例注入到您的 controller。

作為旁注,請記住DbContext已經是一個工作單元,而DbSet已經是一個存儲庫。

除非你有充分的理由用你自己的模式實現來包裝它們,否則你可以(並且在大多數情況下應該)直接使用 EF Core 提供的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM