9

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.

1

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

7 Comments

What is startup.cs and appsettings.json. I don't use ASP.net core. I have remowed DI tag. What is services object?
what you use? winform?
Currently console application.
i edited post. you can check. Ignore startup.cs and appsettings.json.
Thx. That's what I needed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.