c# - 如何使用 EntityFramework 核心来单一化实体

标签 c# entity-framework asp.net-core ef-database-first

最近,我使用 VS2017 创建了一个 ASP.NET Core(多平台)项目和一个用于管理 SQL Server 数据库模型的类库。

实际上我们在生产服务器中有一个数据库,我需要使用 dotnet ef dbcontext scaffold [arguments] [options] ... 命令行生成类,但是我需要在创建 DbContext 类时将类名单数化。

拜托,需要帮助!谢谢

最佳答案

我找到了解决方案!

最好的解决方案是实现 IDesignTimeServices 接口(interface)并使用 inflector 工具,如 https://romiller.com/2017/02/10/ef-core-1-1-pluralization-in-reverse-engineer/ 中所述。 .

要实现此类解决方案,DesignTimeServiceDbContextWriterModelConfigurationRelationalScaffoldingModelFactory 自定义类和 Inflector 类必须驻留在 Startup 类所在的启动项目中。使用包管理器控制台执行以下命令:

Install-Package Microsoft.EntityFrameworkCore.Design 

Install-Package Microsoft.EntityFrameworkCore.Tools

在 Scaffold 过程中,Entity Framework Design 会在 Startup 项目中搜索任何实现了 IDesignTimeServices 的类,并执行其代码。

使用包管理器控制台执行以下命令根据需要替换值,请记住,如果需要将数据库优先进程中的模型类存储到其他项目(例如类库)中,请先在 Visual Studio 包管理器中选择它控制台:

Scaffold-DbContext -provider Microsoft.EntityFrameworkCore.SqlServer -connection "<connection string here...>" -Context MyDbContext -OutputDir "folder path" -StartupProject MyMainProject -Force

就是这样,单数化和任何所需的定制都非常完美!

感谢评论中提供的帮助!

更新:

最近的 Entity Framework Core 2.0 版本改进了单数化/复数化过程,避免了 DbContextWriter、ModelConfiguration 和 RelationalScaffoldingModelFactory 实现的要求,通过一个名为 IPluralizer 的新接口(interface)使这个过程更简单,您可以在实现 Pluralize 和 Singularize 方法的类中使用该接口(interface).

Microsoft.EntityFrameworkCore.Design、Microsoft.EntityFrameworkCore.Tools 的相同包安装是必需的,如果您希望在您的解决方案中使用此 DataBase,还需要 Microsoft.EntityFrameworkCore.SqlServer,但现在实现 IDesignTimeServices 的类只需要在中实现 IPluralizer 的类一个简单的方法:

public class CustomDesignTimeService : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
                => serviceCollection.AddSingleton<IPluralizer, CustomPluralizer>();
}

最后,CustomPluralizer 只是使用了 Inflector 工具类方法:

public class CustomPluralizer : IPluralizer
{
    public string Pluralize(string identifier)
    {
        return Inflector.Pluralize(identifier) ?? identifier;
    }

    public string Singularize(string identifier)
    {
        return Inflector.Singularize(identifier) ?? identifier;
    }
}

如果您不想使用 Inflector 类,只需实现您自己的 Pluralize/Singularize 代码。

这就是我在新的 ASP.NET Core 2.0 项目中必须做的所有事情。希望对您有所帮助!

关于c# - 如何使用 EntityFramework 核心来单一化实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149678/

相关文章:

c# - 无法将 lambda 表达式转换为类型 'string',因为它不是委托(delegate)类型

c# - 英孚。连接未关闭。连接的当前状态是 connecting

c# - 未为加载的控件生成 ASP.NET 客户端 ID

c# - 如果创建了一个未显示的窗口,应用程序不会退出

c# - 在 Code First MVC 应用程序中查询 AspNet Identity 表

c# - Entity Framework 不应用更改

c# - 如何将 Web API .NET Core 3.0 应用程序发布到多个服务器

c# - .NET Core 2.1 - 构建时的 dotnet/exe,缺少包

c# - 如何将两个不同类型的列表合并为一个包含两种类型的新类型列表?

c# - EF Core 子元素的列表和属性之间的相交返回 "ArgumentNullException"