简体   繁体   中英

EF Multiple Schema CodeFirst

How to create tables with multiple schemas in EF with codefirst approach.

i have this Context but it seems only the Schema.Legion is created.

any help would be appreciated.

namespace DotA.Server.Context
{
    public class DotAContext : DbContext
    {
        public DbSet<EFHero> Hero { get; set; }
        public DbSet<EFItem> Item { get; set; }
        public DbSet<EFSkill> Skill { get; set; }
        public DbSet<EFStat> Stat { get; set; }

        private Schema schema;
        private static readonly ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> ModelCache = new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();

        public DotAContext(Schema schema)
            : base("name=DotAConnectionString")
        {
            this.schema = schema;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<EFHero>().ToTable("Hero", Schema.Scourge.ToString());
            modelBuilder.Entity<EFSkill>().ToTable("Skill", Schema.Scourge.ToString());
            modelBuilder.Entity<EFItem>().ToTable("Item", Schema.Scourge.ToString());
            modelBuilder.Entity<EFStat>().ToTable("Stat", Schema.Scourge.ToString());

            modelBuilder.Entity<EFHero>().ToTable("Hero", Schema.Legion.ToString());
            modelBuilder.Entity<EFSkill>().ToTable("Skill", Schema.Legion.ToString());
            modelBuilder.Entity<EFItem>().ToTable("Item", Schema.Legion.ToString());
            modelBuilder.Entity<EFStat>().ToTable("Stat", Schema.Legion.ToString());

            base.OnModelCreating(modelBuilder);
        }
    }
}

You have duplicated/reused the poco EntityNames. Each entity is mapped to a table. It cant be mapped to mutliple tables. Which table should Context.Set<TPoco>() refer to when it is declared twice? In your case, The last definition is winning.

You could

  1. create mutiple contexts. Each context has the enityt mapping required. You can have more than 1 context open at a time. So you can read from one attach to the other. or access 2 contexts.
  2. If you really need the tables inside one context. Then you will need to declare each entity. Perhaps using an abstract base.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM