Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the name of the table to be used by DbContext

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)?

like image 228
noob Avatar asked Oct 16 '14 13:10

noob


People also ask

How to get dbset from dbcontext by type?

2 Answers 2. You can get DbSet from DbContext by Type using the method DbContext.Set(Type entityType). So if you have the model class name as string you should do some mapping to actual clr type.

What is dbcontext in dbcompiledmodel?

DbContext(DbCompiledModel) DbContext(DbCompiledModel) DbContext(DbCompiledModel) Constructs a new context instance using conventions to create the name of the database to which a connection will be made, and initializes it from the given model. The by-convention name is the full name (namespace + class name) of the derived context class.

What is dbcontext class in Entity Framework example?

For example, the context class name for EF_Demo_DB is EF_Demo_DBEntities and derived from the DBContext class as shown below. Note: The class that is derived from the System.Data.Entity.DbContext class is called a context class in the entity framework. What are the responsibilities of DbContext class in Entity Framework?

Can dbcontext choose products table instead of portfolio table?

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.


2 Answers

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.

like image 73
Christoph Fink Avatar answered Oct 27 '22 05:10

Christoph Fink


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

Specifically:

[Table("Portfolio")]
class Product
{

    public string Foo{get;set;}
}
like image 41
spender Avatar answered Oct 27 '22 05:10

spender