实体框架核心RC2表名复数 [英] Entity Framework Core RC2 table name pluralization

查看:70
本文介绍了实体框架核心RC2表名复数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法执行这段代码在EF Core RC 2中的工作?

Is there a way to do what this code did in EF Core RC 2?

protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}


推荐答案

对此没有约定从EF RC2版本开始。这来自EF Core团队:

There is no convention for this as of EF RC2 build. This is from EF Core team:


在过去的EF Core发行版中,实体的表名是
与实体类名称相同。在RC2中,我们现在使用DbSet
属性的名称。如果没有为给定的实体类型
定义DbSet属性,则使用实体类名称。

In past pre-release of EF Core, the table name for an entity was the same as the entity class name. In RC2 we now use the name of the DbSet property. If no DbSet property is defined for the given entity type, then the entity class name is used.



现在,如果要恢复表的RC1命名约定,可以使用以下3种方式:


Now if you want to revert back to the RC1 naming conventions for tables, you have 3 ways to go with:



<强> 1。为DbSet属性选择唯一名称:

一种方法是使DbSet属性名称唯一(我不喜欢)。假设您有一个 Book 实体,并且想要映射到 Book 表:

One way is to singularize your DbSet property names (which I don't like). Say for example you have a Book entity and you want to map to a Book table:

public DbSet<Book> Book { get; set; }



2。使用ToTable()Fluent API:

当然,您始终可以使用fluent API覆盖所有约定,并根据需要指定表名:

You can of course always use fluent API to override any convention in place and dictate the table name to whatever you want:

modelBuilder.Entity<Book>().ToTable("Book");



3。编写自定义约定:

仅因为EF Core RC2没有与此相关的约定,但这并不意味着我们不能编写自己的约定。为此,首先我们需要在 ModelBuilder 对象上创建扩展方法:

Just because EF Core RC2 does not have a convention for this, it doesn't mean we can't write our own. To do so, first we need to create an extension method on ModelBuilder object:

using Microsoft.EntityFrameworkCore.Metadata.Internal;

public static class ModelBuilderExtensions 
{
    public static void RemovePluralizingTableNameConvention(this ModelBuilder modelBuilder)
    {
        foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes())
        {
            entity.Relational().TableName = entity.DisplayName();
        }
    }
}

然后我们简单地称它为从 DbContext 对象上的 OnModelCreating 方法中获得:

And then we simply call it from the OnModelCreating method on our DbContext object:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.RemovePluralizingTableNameConvention();
}



关闭时:

我不喜欢复数表名,并且我比其他选项更喜欢最后一个选项。就是说,这是我个人的观点,其他开发人员可能会发现这三种方式中的任何一种都比其他方式更有利,并选择使用它:)

I don't like plural table names and I like the last option better than the others and went with that. That said, it's my personal opinion and other developers might find any of these 3 ways more favorable than the others and choose to go with that :)

这篇关于实体框架核心RC2表名复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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