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

喜夏-厌秋 提交于 2019-12-22 05:12:06

问题


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


回答1:


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.




回答2:


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

Specifically:

[Table("Portfolio")]
class Product
{

    public string Foo{get;set;}
}


来源:https://stackoverflow.com/questions/26405685/how-to-specify-the-name-of-the-table-to-be-used-by-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!