如何指定要由DbContext使用的表的名称 [英] How to specify the name of the table to be used by DbContext

查看:204
本文介绍了如何指定要由DbContext使用的表的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前的问题的后续问题。我的印象是,如果数据库中有多个表,则将使用 DbSet 变量的名称来标识表。

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.

然而,在链接的问题中,很明显, DbContext 正在选择 code>表,而不是投资组合表,即使变量的名称是投资组合。我仍然可以将变量名改为任何东西,而且我仍然收到数据。

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.

所以我的问题是如何通过 DbContext 映射表?我需要在项目中添加更多的表,并且不知道如何使用单个 DbContext 对象(或者应该使用单独的 DbContext 对于同一数据库中的单独表)?

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

推荐答案

您可以在实体上执行以下操作:

You can do the following on the entity:

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

按照惯例,该表以多个实体名称命名。

所以 DbSet< Product> 将默认存储/查找名为 Products 的表。

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.

这篇关于如何指定要由DbContext使用的表的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆