ComponentModel data annotations: explicitly defining database table name separate from class name in code RRS feed

  • Question

  • User-734459410 posted

    So I'm working on a photo gallery as a project, and have a class named Category (used to categorize pictures), which holds basic information about a category (basically a unique ID that can be referenced in other tables, and a name field):

    public class Category
      public int Id;
      [Display(Name = "Category Name")]
      public string Name;

    I'm using E-F code first in this project, and wanted to know if there is a way that I can tell E-F / SQL server to use the table name "Categories" instead of "Category" which it would pick up by default based on the class name when the E-F relationship data model is added/built.  Is there a annotation I can use to specify the name of the table that E-F should use rather than the class name?  I want to specify this, so that when I create instances of this class (Category) it's easy to read, and doesn't look like:

    public cat = new Categories();
    // I don't want this
    public cat = new Category();
    // I want this
    // But I want SQL Server / E-F to call the entity "Categories" in the database


    Thursday, January 11, 2018 2:44 AM

All replies

  • User-734459410 posted

    Nevermind, I think that I can use [Table("name")] to do this, unless anyone thinks this might not be a good idea....?

    Thursday, January 11, 2018 2:48 AM
  • User1400794712 posted

    Hi cbassett,

    Use [Table("name")] is really a good idea to do it. So, I post here just to provide another idea.

    In the Context class, override OnModelCreating to specify the name of table:

    public class TestContext : DbContext
        public DbSet<Category> Category { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)

    For more information, please refer to this article:


    Best Regards,


    Friday, January 12, 2018 7:09 AM