Pass Connection String to Code-First Dbcontext

Pass connection string to code-first DbContext

After reading the docs, I have to pass the name of the connection string instead:

var db = new NerdDinners("NerdDinnerDb");

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


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");

Pass connection string to EF DbContext code first

Turns out that the connection string is cached in a readonly string for MigrateDatabaseToLatestVersion from this answer. I just had to update the class to:

public class StudentContext : DbContext
{
public StudentContext(string connectionString) : base(connectionString)
{
}

protected override void OnModelCreating(DBModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>(true)); //Passing true here to reuse the client context triggering the migration
}

public DbSet<Student> Students {get; set;}
}

passing connection string to DBcontext without using app.config

A DbContext class has a constructor that you can pass your connection string while creating a new instance of it. The best approach here is to make a constructor for your Class A too and take your connection string arguments from outside, not inside your class. But if you're so sure about using having you connection string in your class, at least you should make it optional like this.

    public class MyDbContext : Dbcontext , IA
{
public static readonly _defaultConnString = nugget.connString();

public class MyDbContext() : base(_defaultConnString) { }

public class MyDbContext(string connString) : base(connString) { }
}

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

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;
}

How to specify an Entity Framework Connection String in API Project

In EF core you don't need to send a connection to the base class with the constructor, just follow this approach:

public partial class LocalContext : DbContext
{
public LocalContext ()
{
}

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

public virtual DbSet<Weapon> Weapons { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//warning You can move this code to protect potentially sensitive
information
//in connection string.

optionsBuilder.UseSqlServer("Data Source= .;Initial
Catalog=Weapons;Trusted_Connection=True;");
}
}
}

How to pass connection string to DataContext in EF6

If your objective is to have separate connection strings for different environments then you should not be separating the connection string variables. Instead vary the value of the connection string.

Configure your DBContext object to be like the follwing:

public partial class HAZID_DataContext : DbContext
{
public HAZID_DataContext()
{
}

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

//Other codes goes here

}

Then inject the connection string in app startup:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<HAZID_DataContext>(opts =>
opts.UseSqlServer(Configuration.GetConnectionString("HAZIDDEV")));

...
}

Then in the appsettings.json file for MVC Core:

{
"ConnectionStrings": {
"HAZIDDEV": "Data Source=.\SQLEXPRESS2012;Initial Catalog=dbname;Persist Security Info=True;User ID=abc;Password=abc"
}
}

Or Read from web.config or other config file this way:

ConfigurationManager.ConnectionStrings["HAZIDDEV"].ConnectionString;

Just change the value of the connection string based on environments. Or have multiple connection strings as required.



Related Topics



Leave a reply



Submit