Last active
April 26, 2022 16:47
-
-
Save Guifgr/27aa00361514433be18e6c22eace1fe7 to your computer and use it in GitHub Desktop.
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
using Domain.Models; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.EntityFrameworkCore.Infrastructure; | |
using Microsoft.Extensions.Configuration; | |
namespace Infrastructure.Database.Context | |
{ | |
public class MssqlContext : DbContext | |
{ | |
public MssqlContext() | |
{ | |
} | |
public MssqlContext(DbContextOptions<PdgContext> options) : | |
base(options) | |
{ | |
} | |
public DbSet<User> Users { get; set; } = null!; | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
if (!optionsBuilder.IsConfigured || | |
!optionsBuilder.Options.Extensions.OfType<RelationalOptionsExtension>().Any(ext => | |
!string.IsNullOrEmpty(ext.ConnectionString) || ext.Connection != null) && | |
!optionsBuilder.Options.Extensions.Any(ext => | |
ext is not RelationalOptionsExtension && ext is not CoreOptionsExtension)) | |
optionsBuilder.UseSqlServer(GetConnectionString("MssqlConnection")); | |
base.OnConfiguring(optionsBuilder); | |
} | |
private static string GetConnectionString(string connectionStringName) | |
{ | |
var configurationBuilder = | |
new ConfigurationBuilder().AddJsonFile("appsettings.json", true, false); | |
var configuration = configurationBuilder.Build(); | |
return configuration.GetConnectionString(connectionStringName); | |
} | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
modelBuilder.Entity<User>(entity => | |
{ | |
entity.Property(e => e.Guid).HasDefaultValueSql("NEWID()"); | |
entity.HasIndex(e => e.Guid).IsUnique(); | |
}); | |
base.OnModelCreating(modelBuilder); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment