Kevin M
Kevin M

Reputation: 452

Entity Framework 7 - single dbcontext, different schemas

I have an ASP.NET 5 web api, and I was hoping to use a single dbcontext for multiple models. These models point to tables with different schemas in my database.

The models below contain multiple classes

Simplified a little: Auth.cs

public class MyContext : DbContext
    {
        public DbSet<Auth.App> Apps { get; set; }
        public DbSet<Auth.Permission> Permissions { get; set; }
        public DbSet<Study.StudyLink> StudyLinks { get; set; }
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entity in modelBuilder.Model.GetEntityTypes())
        {
            if (entity.Name.Contains("Auth+"))
            {
                modelBuilder.HasDefaultSchema("auth"); // Switch to the auth schema
                modelBuilder.Entity(entity.Name).ToTable(entity.Name.Replace("myproject.Models.Auth+", string.Empty));
            }
            if (entity.Name.Contains("Study+"))
            {
               modelBuilder.HasDefaultSchema("study"); // Switch to the study schema
               modelBuilder.Entity(entity.Name).ToTable(entity.Name.Replace("myproject.Models.Study+", string.Empty));
            }
        }
    }

Using just the Auth model, I was able to change the default schema and can access the tables no problem.. when I add the Study model, the modelBuilder.Model.GetEntityTypes() foreach brings up both the Auth and Study models, so is switching the default schema, meaning I can't access the Auth schema because it switches to study.

Is there some way I can apply the schema without using HasDefaultSchema() or do I need to create a new context for each schema I use in my database?

Thanks

Upvotes: 1

Views: 398

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You can add your schema to the .ToTable("tableName", "schemaName"):

if (entity.Name.Contains("Auth+"))
{
   modelBuilder.Entity(entity.Name).ToTable(entity.Name.Replace("myproject.Models.Auth+", string.Empty),"auth");
}

https://msdn.microsoft.com/en-us/data/jj591617.aspx?f=255&MSPPError=-2147217396#2.3

Upvotes: 1

Related Questions