Fernando Pardo
Fernando Pardo

Reputation: 91

EF and dynamic table names

I am checking if there is way to dynamically change the table mapped to an Entity in EF 6. The schema of the table doesn't change, just the name. For example, I have an Entity called Orders, then I need to assign this Entity to a SQL view dynamically created when the program runs. The name of the view is generated in run-time, so I need to map that view name to the Orders entity in run-time. Any idea how to do this? Thanks in advance. -Fernando

Upvotes: 1

Views: 264

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89406

So long as the table name doesn't change while your program is running, you can just map in in OnModelCreating. Eg

   class Db: DbContext
    {

        public DbSet<Student> Students { get; set; }
        public DbSet<ClassRoom> Classrooms { get; set; }

        public DbSet<StudentToClassRoom> StudentToClassRoom { get; set; }

        private string GetStudentTableName()
        {
            return "Student123";
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().ToTable(GetStudentTableName());
            base.OnModelCreating(modelBuilder);
        }

    }

Upvotes: 2

Related Questions