9

This is a followback question from my earlier question. I was under the impression that if there're more than one table in the database, the name of the DbSet variable will be used to identify the table.

However in the linked question it was clear that the DbContext was choosing Products table instead of Portfolio table even if the name of the variable was Portfolio. I can still change the variable name to anything and I am still getting data.

So my question is how the tables are mapped by DbContext? I need to add few more tables in the project and have no idea how would I do that using a single DbContext object (or should I use separate DbContext for separate Tables in the same database)?

Community
  • 1
  • 1
0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
  • If you wanted the Portfolio table, why is your DBSet typed as `DbSet` instead of `DbSet`? It is the _entity type_ that is used to determine the table name, not the variable name. – Chris Dunaway Oct 16 '14 at 13:40
  • @ChrisDunaway That was a misconception on my end. I was curious on how the mappings of tables are done. The answers provided the clarification. – 0xC0DED00D Oct 16 '14 at 13:50

2 Answers2

19

You can do the following on the entity:

[Table("Portfolio")]
public class Product { /* ... */ }

By convention the table is named after the plural of the entities name.
So a DbSet<Product> will by default be stored / looked up in a table named Products.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
  • And how to remove this default "pluralization" without the need to mark every entity with its table name? – FindOutIslamNow Mar 01 '17 at 11:31
  • @FindOutIslamNow: http://stackoverflow.com/questions/4796543/how-do-i-singularize-my-tables-in-ef-code-first - but to give my 2 cents: As a table stores e.g. more than one product a singluar name is wrong IMO ;-)... – Christoph Fink Mar 01 '17 at 12:10
3

Take a look at System.ComponentModel.DataAnnotations.Schema.TableAttribute.

Specifically:

[Table("Portfolio")]
class Product
{

    public string Foo{get;set;}
}
spender
  • 117,338
  • 33
  • 229
  • 351