Last active
January 3, 2024 19:33
-
-
Save tcartwright/acfc8f743efb199c1c2f4b050f676672 to your computer and use it in GitHub Desktop.
C#: Read only configuration context for sql server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial class MyContextReadOnly : MyContext | |
{ | |
private readonly string _connectionString = null; | |
public MyContextReadOnly(DbContextOptions<MyContextReadOnly> options) : base(options) | |
{ | |
var sqlServerOptionsExtension = options.FindExtension<SqlServerOptionsExtension>()!; | |
_connectionString = sqlServerOptionsExtension?.ConnectionString!; | |
} | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
base.OnConfiguring(optionsBuilder); | |
if (!string.IsNullOrWhiteSpace(_connectionString)) | |
{ | |
var builder = new DbConnectionStringBuilder | |
{ | |
ConnectionString = _connectionString | |
}; | |
builder["ApplicationIntent"] = "ReadOnly"; | |
optionsBuilder.UseSqlServer(builder.ConnectionString); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment