在 EF Core 2 中使用单一表名 [英] Using Singular Table Names with EF Core 2

查看:17
本文介绍了在 EF Core 2 中使用单一表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的域类名称与我的 db 表名称匹配(没有复数形式).

I want my domain class name to match my db table name (no pluralisation).

在 EF Core 1.1 中,我使用以下代码来做到这一点:

In EF Core 1.1, I used this code to do that:

public static void RemovePluralisingTableNameConvention(this ModelBuilder modelBuilder)
{
    foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
    {
        entityType.Relational().TableName = entityType.DisplayName();
    }
}

在 EF Core 2.0 中,此代码无法编译,因为 Relational() 不是 IMutableEntityType 上的方法.无论如何,在 EF Core 2.0 中,他们添加了 IPluralizer,记录在此处:

In EF Core 2.0, this code doesn't compile as Relational() is not a method on IMutableEntityType. Anyway, in EF Core 2.0, they have added IPluralizer, documented here:

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/what-is-new/index.md#pluralization-hook-for-dbcontext-脚手架

没有多少示例可以展示如何实现与我之前相同的行为.关于如何在 EF Core 2 中删除复数的任何线索?

There aren't many examples to show how to achieve the same behaviour that I had before. Any clue of how to remove pluralisation in EF Core 2?

推荐答案

您可以使用完全相同的代码.Relational()RelationalMetadataExtensions 类在 Microsoft.EntityFrameworkCore.Relational.dll assembly 中,所以请确保你正在引用它.

You can use exactly the same code. Relational() is extension method defined in the RelationalMetadataExtensions class inside Microsoft.EntityFrameworkCore.Relational.dll assembly, so make sure you are referencing it.

IPluralizer怎么样,从链接中可以看出它只是一个DbContext Scaffolding的Pluralization hook,即从数据库中生成实体类,用于单数化实体类型名称和复数 DbSet 名称.它不用于表名生成.表映射部分解释了默认的表名称约定文档:

What about IPluralizer, as you can see from the link it's just a Pluralization hook for DbContext Scaffolding, i.e. entity class generation from database, used to singularize entity type names and pluralize DbSet names. It's not used for table name generation. The default table name convention is explained in Table Mapping section of the documentation:

按照惯例,每个实体将被设置为映射到一个与 DbSet 属性同名的表,该属性在派生上下文中公开实体.如果给定实体没有包含 DbSet,则使用类名.

By convention, each entity will be setup to map to a table with the same name as the DbSet<TEntity> property that exposes the entity on the derived context. If no DbSet<TEntity> is included for the given entity, the class name is used.

这篇关于在 EF Core 2 中使用单一表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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