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

后端 未结 5 894
生来不讨喜
生来不讨喜 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 12:57

    Startup.cs for static connection

    services.AddScoped<MyContext>(_ => new MyContext(Configuration.GetConnectionString("myDB")));
    

    Table1Repository.cs for dynamic connection

    using (var _context = new MyContext(@"server=....){
    context.Table1....
    }
    

    MyContext.cs

    public MyContext(string connectionString) : base(GetOptions(connectionString))
    {
    }
    
    private static DbContextOptions GetOptions(string connectionString)
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
    }
    
    0 讨论(0)
  • 2020-12-25 13:00

    IMO best practice:

    add to your configuration.json:

         "ConnectionStrings": {
        "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
      }
    

    and to initialize section:

    services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));
    
    0 讨论(0)
  • 2020-12-25 13:01

    Another option would be to call the base constructor that takes a DbContextOptions:

    public BooksContext(string connectionString) : base(GetOptions(connectionString))
    {
    }
    
    private static DbContextOptions GetOptions(string connectionString)
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
    }
    
    0 讨论(0)
  • 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<MyDbContext>(options => options.UseSqlServer(connection));
    services.AddScoped<IMyDbContext, MyDbContext>();
    

    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
    }
    
    0 讨论(0)
  • 2020-12-25 13:14

    So I searched all over for a solution to my issue which was I needed to dynamically connect to a database based on data that I do not have until time to do the connecting. Basically, dynamic context. I did not have the data being passed on the URL, and I did not have a short list of possible databases to attach to). So, here is my solution to the issue posed. This code will allow you to use the appsettings.json file to define the connection string with a placeholder to be replaced at run time by the code. This can be done within a controller or some other class as you see fit.

    I am using both a static context and a dynamic context but you could use dynamic only.

    Hopefully someone will stumble upon this and say thank god...although probably just as likely someone will say, this guy is an idiot. Either way, enjoy.

    using System;
    using System.Globalization;
    using System.Linq;
    using Microsoft.Extensions.Configuration;
    
    namespace CallCenter.Repositories
    {
        public class TestRepository : ITestRepository 
        {
            private readonly InsuranceContext _context;
            public TestRepository InsuranceContext context)
            {
                _context = context;
            }
    
            public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
            {
                var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
    
                var configuration = builder.Build();
                var connectionString = configuration.GetConnectionString("DefaultConnection");
    
    
                    var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));
    
                    var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
                    if (company != null)
                    {
                        companyId = company.CompanyId.ToString();
                    }
    
    ... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
                }
    
            }
        }
    }
    
    //The AgencyContext class would look like this:
    
    using Microsoft.EntityFrameworkCore;
    
    namespace CallCenter.Entities
    {
        public class AgencyContext : DbContext
        {
            public AgencyContext(string connectionString) : base(GetOptions(connectionString))
            {
    
            }
    
            private static DbContextOptions GetOptions(string connectionString)
            {
                return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
            }
    
            public DbSet<Companys> Companys { get; set; }
        }
    }
    
    //The startup.c IServiceProvider module has this:
    
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
    
                services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
                services.AddScoped<ITestRepository , TestRepository >();
    ....
    }
    

    And finally the appsettings.jason file would have this in it:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
    }
    }
    
    0 讨论(0)
提交回复
热议问题