Friday, May 10, 2013

How to specify the table name for a child table in a many-to-many relationship using ASP.NET MVC EF5 Code First


Here's some typical POCO code for using EF5 code first:

    public class Book
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Author> Authors { get; set; }
    }

    public class Author
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Book> Books { get; set; }
    }

EF will generate the following tables:

  • Books
  • Authors
  • BookAuthors

So, what if you wanted to control the naming of the tables EF is generating? You might do this:

    [Table("bookstore_Books")]
    public class Book
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Author> Authors { get; set; }
    }

    [Table("bookstore_Authors")]
    public class Author
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Book> Books { get; set; }
    }

Here are the table names now:

  • bookstore_Books
  • bookstore_Authors
  • BookAuthors
Not really what we want.

Unfortunately, you cannot control the name of the child table using simple DataAnnotations. You can, however, use the Fluent API. Simply override the OnModelCreating method in your DbContext class.

    public class MegaStoreDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Book>()
                .HasMany(a => a.Authors)
                .WithMany(b => b.Books)
                .Map(mc =>
                {
                    mc.MapLeftKey("BookID");
                    mc.MapRightKey("AuthorID");
                    mc.ToTable("bookstore_BookAuthors");
                });
        }
        public DbSet<Book> Books{ get; set; }
        ....
    }

Now, here are your tables:

  • bookstore_Books
  • bookstore_Authors
  • bookstore_BookAuthors

Happy Coding!