Skip to content

Instantly share code, notes, and snippets.

@223n
Last active Jun 17, 2018
Embed
What would you like to do?
DbContextを継承したクラスの実装例
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace SampleProject.Models
{
public class Context : DbContext
{
public Context() { }
public Context(DbContextOptions<Context> options) : base(options) { }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<UserRole> UserRoles { get; set; }
public static readonly LoggerFactory SampleLoggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information, true) });
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder
.UseLoggerFactory(SampleLoggerFactory)
.UseNpgsql("Server=localhost;Database=sso;Username=*****;Password=*****;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.ToTable(nameof(User));
entity.Property(e => e.Id).HasColumnName(nameof(User.Id));
entity.Property(e => e.Name).HasColumnName(nameof(User.Name));
entity.Property(e => e.LastUpdated).HasColumnName(nameof(User.LastUpdated));
entity.Property(e => e.GCRecord).HasColumnName(nameof(User.GCRecord));
});
modelBuilder.Entity<Role>(entity => {
entity.ToTable(nameof(Role));
entity.Property(e => e.Id).HasColumnName(nameof(Role.Id));
entity.Property(e => e.Name).HasColumnName(nameof(Role.Name));
entity.Property(e => e.LastUpdated).HasColumnName(nameof(Role.LastUpdated));
entity.Property(e => e.GCRecord).HasColumnName(nameof(Role.GCRecord));
});
modelBuilder.Entity<UserRole>(entity =>
{
entity.ToTable(nameof(UserRole));
entity.Property(e => e.Id).HasColumnName(nameof(UserRole.Id));
entity.Property(e => e.UserId).HasColumnName(nameof(UserRole.UserId));
entity.Property(e => e.RoleId).HasColumnName(nameof(UserRole.RoleId));
entity.Property(e => e.LastUpdated).HasColumnName(nameof(UserRole.LastUpdated));
entity.Property(e => e.GCRecord).HasColumnName(nameof(UserRole.GCRecord));
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment