Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将ASP.NET Core MVC中的存储库模式与Entity Framework Core一起使用?_C#_Asp.net Core_Entity Framework Core_Repository Pattern - Fatal编程技术网

C# 如何将ASP.NET Core MVC中的存储库模式与Entity Framework Core一起使用?

C# 如何将ASP.NET Core MVC中的存储库模式与Entity Framework Core一起使用?,c#,asp.net-core,entity-framework-core,repository-pattern,C#,Asp.net Core,Entity Framework Core,Repository Pattern,我创建了一个项目ASP.NET Core 3 MVC,我需要使用数据库优先的方法通过Entity Framework Core处理数据库。现在有两个数据库:MSSQL和PostgreSQL。我需要以最简单的形式实现存储库模式。我该怎么做 这两个数据库都有表:dbo.Author(public.Author)、dbo.Book(public.Book)和dic.BookType以及相应的外键。应在“ConfigureServices”方法中指定要使用的数据库(如果可能)。我的目标不是依赖于特定的数

我创建了一个项目ASP.NET Core 3 MVC,我需要使用数据库优先的方法通过Entity Framework Core处理数据库。现在有两个数据库: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();
     }
    
    公共接口i假设,其中T:class
    {
    任务GetAll();
    任务GetById(TId id);
    无效添加(T实体);
    无效更新(T实体);
    无效删除(T实体);
    任务保存更改();
    }
    
  • 创建“Repository.cs”:

    公共抽象类存储库:IRepository其中tenty:class
    {
    私有只读DbContext\u context;
    公共存储库(DbContext上下文)
    {
    _上下文=上下文;
    }
    公共异步虚拟任务GetAll()
    {                
    返回wait_context.Set().ToListAsync();
    }
    公共异步虚拟任务GetById(TId id)
    {                
    返回wait_context.Set().FindAsync(id);
    }
    公共虚拟空添加(TEntity实体)
    {                
    _context.Set().Add(实体);
    }
    公共虚拟无效更新(TEntity实体)
    {
    _更新(实体);
    }                
    公共虚拟无效删除(TEntity实体)
    {
    _context.Set().Remove(实体);
    }
    公共异步虚拟任务SaveChanges()
    {
    return wait_context.saveChangesSync();
    }
    }
    
  • 为每个实体创建了一个存储库:(您真的需要为PostgreSQL创建另一个存储库吗?)

    公共类BookRepository:存储库
    {
    PublicBookRepository(Microsoft.EntityFrameworkCore.DbContext上下文):基础(上下文)
    {
    }
    }
    
  • 在“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 void配置服务(IServiceCollection服务)
    {
    /*
    字符串connStr=Configuration.GetConnectionString(“MSSQLConnection”);
    services.AddDbContext(选项=>
    options.UseSqlServer(connStr));
    */
    字符串connStr=Configuration.GetConnectionString(“PostgreSQLConnection”);
    services.AddDbContext(选项=>
    选项。使用npgsql(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();
             }
        }
    
    公共类HomeController:控制器
    {        
    受保护的/*DbContext*/Common.ApplicationContext\u context;
    公共HomeController(Common.ApplicationContext上下文)
    {
    _上下文=上下文;
    }                          
    公共异步任务索引()
    {
    var bookRepo=new Common.Repositories.BookRepository(_context);
    var books=await bookRepo.GetAll();
    // ...
    返回视图();
    }
    }
    
  • onfigure
    方法中注册您的
    BookRepository
    ,如
    services.AddScoped()
  • 让框架通过构造函数注入
    BookRepository
    实例到控制器

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


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

    我强烈建议您阅读以下答案:
        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();
             }
        }