-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserContext.cs
More file actions
64 lines (45 loc) · 2.11 KB
/
UserContext.cs
File metadata and controls
64 lines (45 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using DataContextContainer.Models;
using Microsoft.EntityFrameworkCore;
namespace DataContextContainer
{
public class UserContext : DbContext, IHaveSchemaName
{
private readonly ISchemaNameProvider schemaNameProvider;
public string SchemaName { get; set; } = "public";
public UserContext()
{
}
public UserContext(DbContextOptions<UserContext> options, ISchemaNameProvider schemaNameProvider) : base(options)
{
this.schemaNameProvider = schemaNameProvider;
this.SchemaName = this.schemaNameProvider.SchemaName;
System.Console.WriteLine("Running on schema name" + this.SchemaName);
}
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Category> Categories { get; set; }
public DbSet<Filter> Filters { get; set; }
// public virtual DbSet<UserConfig> UserConfigs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;DataBase=shared;Username=postgres;Password=pass123");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(this.SchemaName);
modelBuilder.Entity<Product>().ToTable(nameof(Products), r => r.ExcludeFromMigrations());
//modelBuilder.Entity<User>().ToTable("Users", "public");
//modelBuilder.Entity<UserConfig>().ToTable("UserConfigs", "public");
modelBuilder.Entity<UserProduct>().HasKey(r => new { r.UserId, r.ProductId });
modelBuilder.Entity<UserProduct>().HasOne(r => r.Product).WithOne().HasForeignKey<UserProduct>(r => r.UserId);
modelBuilder.Entity<UserProduct>().HasOne(r => r.User).WithOne().HasForeignKey<UserProduct>(r => r.UserId);
base.OnModelCreating(modelBuilder);
}
}
public interface IHaveSchemaName
{
string SchemaName { get; set; }
}
}