How can I implement DbContext Connection String in .NET Core?

后端 未结 5 897
生来不讨喜
生来不讨喜 2020-12-25 12:14

My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

Pass connectio

5条回答
  •  被撕碎了的回忆
    2020-12-25 13:14

    Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.

    1) Add a line to your appsettings.json:

    "DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",
    

    2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:

    var connection = Configuration["DbConnectionString"];
    

    3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:

    services.AddDbContext(options => options.UseSqlServer(connection));
    services.AddScoped();
    

    Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext

    4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:

    public MyController(IMyDbContext context)
    {
        _context = context  // store for later use
    }
    

提交回复
热议问题