How do I pass connection string to DBContext in Entity Framework Core?
Asked Answered
K

1

8

Is it possible to configure/pass connection string to the DbContext in the constructor?

public partial class MyContext : DbContext
{
    public MyContext() { }
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
}

MyContext opt = new MyContext("con_str");

rather than hard coding it in:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(
        @"Server=(localdb)\mssqllocaldb;Database=MyDB;Integrated Security=True");
}

How do I use:

DbContextOptions<MyContext> opts;

The following answer: Pass connection string to code-first DbContext does not work.

Klein answered 18/8, 2020 at 8:33 Comment(1)
Does this answer your question? .Net Core passing connection string to DBContext classAustin
P
7

Startup.cs

services.AddDbContext<YourDbContext>(options =>
{
     options.UseSqlServer(Configuration.GetSection("YourConn").Value);
     options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});

appsettings.json

"YourConn": "yourconnectionstring"

EDITED

YourDbContext.cs

public partial class MyContext : DbContext
{
    private string _conn = "";
    public MyContext(string conn) 
    { 
        _conn = conn;
    }
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
         optionsBuilder.UseSqlServer(_conn);
    }
}

Then you can use

MyContext opt = new MyContext("con_str");
Paolo answered 18/8, 2020 at 8:38 Comment(7)
What is startup.cs and appsettings.json. I don't use ASP.net core. I have remowed DI tag. What is services object?Klein
what you use? winform?Paolo
Currently console application.Klein
i edited post. you can check. Ignore startup.cs and appsettings.json.Paolo
Thx. That's what I needed.Klein
Thank you @Asherguru, anyway I really had to implement this on bad condition that I really hate at... *look into my code, and cry...Davina
DbContextOptions doesnt exist for me?Medication

© 2022 - 2024 — McMap. All rights reserved.