Created
August 21, 2022 19:30
-
-
Save ScriptBytes/10a05744fa42621c199cda40345ecc1a to your computer and use it in GitHub Desktop.
A very simple database context file for a Todo API.
This file contains hidden or 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 class TodoContext : DbContext | |
{ | |
private readonly IConfiguration config; | |
public TodoContext(DbContextOptions options, IConfiguration config) : base(options) | |
{ | |
this.config = config; | |
} | |
public DbSet<Todo> Todos { get; set; } | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
var envVariableName = config.GetValue<string>("EnvKeys:TodoDbConn"); | |
var connectionString = Environment.GetEnvironmentVariable(envVariableName); | |
if (string.IsNullOrEmpty(connectionString)) | |
{ | |
throw new Exception($"The environment variable {envVariableName} is not set."); | |
} | |
optionsBuilder.UseSqlServer(connectionString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment