【问题标题】:Carrying Entity Framework Core context through to Data layer将 Entity Framework Core 上下文传送到数据层
【发布时间】:2020-08-11 19:03:12
【问题描述】:

我使用命令将现有数据库搭建到数据层项目中

Scaffold-DbContext Command

我还有一个 ASP.NET MVC 项目。

在我的Startup.csConfigureServices 方法中,我有

services.AddDbContext<GlassesMVDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<GlassesMVDataContext>();

我的appsetting.json 中有一个连接字符串。

我的数据上下文有一个构造函数

public GlassesMVDataContext(DbContextOptions<GlassesMVDataContext> options)
        : base(options)
{
}

在数据层我希望能够做这样的事情:

using (var context = new GlassesMVDataContext())
{
}

我希望能够使用连接字符串并让上下文在数据层中理解这一点。

我如何做到这一点?

【问题讨论】:

    标签: asp.net-mvc entity-framework-core


    【解决方案1】:

    当您调用“services.AddDbContext(options => ...)”时,您已经将 DbContext 提供给依赖注入 (DI) 系统,因此,连接字符串已经设置,所以让我们采用这种方法.

    在此示例中,我假设 DbContext 将用于从服务构造函数中的 DI 解析的服务中:

    public interface IMyDataService
    {
       void DoSomething();
    }
    
    public class MyDataService: IMyDataService
    {
       private GlassesMVDataContext  _context;
    
       public MyDataService(GlassesMVDataContext context)
       {
          // The connection string is already set in Startup.cs
          _context = context;
       }
    
       public void DoSomething()
       {
          // Do something with _context here....
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2020-07-30
      • 1970-01-01
      • 2021-10-02
      • 2014-01-04
      相关资源
      最近更新 更多