简体   繁体   English

数据库优先实体框架核心的自定义脚手架逻辑

[英]Custom scaffolding logic for database first Entity Framework Core

I'm new to Entity Framework Core as I'm currently migrating over from EF6. 我是Entity Framework Core的新手,因为我目前正在从EF6迁移过来。 We use a database first model. 我们使用数据库优先模型。

I've created a .Net Standard class library where I've imported EF Core and have used the scaffolding command in VS to import one of my tables as a test - which worked. 我创建了一个.Net Standard类库,在其中导入了EF Core,并在VS中使用了scaffolding命令将我的一张表作为测试导入-可以正常工作。

We have a couple of different replica databases that we use for geo-redundancy and reporting purposed, but all have the same model. 我们有几个不同的副本数据库,这些副本数据库用于地理冗余和报告目的,但是都具有相同的模型。

I've set up the different connection options, somewhat like point 2 in the answer in this post Using Entity Framework Core migrations for class library project so we can support connections to the different databases. 我已经设置了不同的连接选项,有点像本文“ 使用Entity Framework Core迁移进行类库项目 ”中答案中的第2点,因此我们可以支持到不同数据库的连接。

Now I want to go about adding the rest of the tables in. I have seen mention of Migrations, but that seems to be for code first models. 现在,我要继续添加其余表。我已经看到了关于Migrations的提及,但这似乎是针对代码优先模型的。

I then tried to use the "-Force" command on the scaffolding, which did import an additional table, but I lost my multi-database support. 然后,我尝试在脚手架上使用“ -Force”命令,该命令的确导入了另一个表,但是我失去了对多数据库的支持。

In EF6 I had this logic in the Context.tt file, so when I retrieved updates from the database it would retain the custom connection options I had. 在EF6中,我在Context.tt文件中具有此逻辑,因此当我从数据库中检索更新时,它将保留我具有的自定义连接选项。

Is there a way to replicate this in EF Core or something I am missing? 有没有一种方法可以在EF Core中复制此文件或我缺少的文件?

Also, for something as simple as a new column on a table, should I still run the same command? 此外,对于像表上的新列这样简单的事情,我是否仍应运行相同的命令?

Thanks in advance, 提前致谢,

David 大卫

* UPDATED * * 更新 *

I ended up using EF Core Power Tools which is a great package and allows complete control over the model, much like the context.tt file used to. 我最终使用了EF Core Power Tools,它是一个很棒的软件包,可以完全控制模型,就像以前的context.tt文件一样。

For anyone looking in future, I reverse engineered and used the Handlebars templates in EF Core Power Tools. 对于未来的任何人,我都对EF Core Power Tools中的Handlebars模板进行了反向工程和使用。 I pass the 3 connection strings I use in the startup of the application and can then set optional booleans to indicate which connection to use - an enum may be more elegant for anyone starting again but this makes migration easier for us. 我传递了在应用程序启动时使用的3个连接字符串,然后可以设置可选的布尔值来指示要使用的连接-对于重新开始的人来说,枚举可能更优雅,但这使我们更容易迁移。 In the DbConstructor.hbs, I updated it to: 在DbConstructor.hbs中,我将其更新为:

{{spaces 8}}public {{class}}(bool ReadOnlyDatabase = false, bool ReportsDatabase = false) : base()
{{spaces 8}}{ 
            if (ReadOnlyDatabase)
                _connectionString = ReadOnlyContext;
            else if (ReportsDatabase)
                _connectionString = ReportsContext;
            else
                _connectionString = ReadWriteContext;
{{spaces 7}} }

The DbContext.hbs file is: DbContext.hbs文件是:

{{> dbimports}}

namespace {{namespace}}
{
    public partial class {{class}} : DbContext
    {
        public static string ReadWriteContext = "";
        public static string ReadOnlyContext = "";
        public static string ReportsContext = "";

        private readonly string _connectionString;
{{{> dbsets}}}
{{#if entity-type-errors}}
{{#each entity-type-errors}}
{{spaces 8}}{{{entity-type-error}}}
{{/each}}

{{/if}}

{{{> dbconstructor}}}

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(_connectionString);
        }
{{{on-model-creating}}}
    }
}

Supply a DbContextOptions to the constructor: 向构造函数提供DbContextOptions:

    public MetadataContext(DbContextOptions<MetadataContext> options)
        : base(options)
    {
    }

Maybe EF Core Power Tools can help you? 也许EF Core Power Tools可以为您提供帮助? (I am the author) (我是作者)

You need to post more of your code so we can see what's going on. 您需要发布更多代码,以便我们了解发生了什么。 At a guess it sounds like you are customizing the generated context class. 听起来好像您正在自定义生成的上下文类。 It will be overwritten with each scaffold operation and as you note the migration support is there to drive db Schema updates from model changes. 您将在每次使用脚手架的操作中将其覆盖,并且如您所述,迁移支持可用于通过模型更改来驱动db Schema更新。 Ie it's for code first. 即,首先是代码。

The db first scaffold approach seems that to be written with the expectation that the scaffold will be done once and thereafter models and contexts will be manually updated. db的第一个脚手架方法似乎是在编写该脚手架的期望下进行的,其后模型和上下文将被手动更新。 We have a workflow that involves re scaffolding the DbContext in response to db schema updates and consequently do three things: 我们有一个工作流程,涉及重新搭建DbContext以响应数据库模式更新,因此需要做三件事:

  • scaffold a localhost or SSPI db so the embedded connection string contains no passwords of value. 将本地主机或SSPI数据库设置为脚手架,以便嵌入式连接字符串不包含任何值值的密码。
  • tolerate the annoying warning in CI/CD about the connection string the scaffolder generates each time that cant be disabled. 容忍CI / CD中有关脚手架每次无法禁用时生成的连接字符串的恼人警告。
  • we use extension methods to add functionality to the DbContext when necessary so we never need to alter the generated code. 我们在必要时使用扩展方法向DbContext添加功能,因此我们无需更改生成的代码。

Now I would not suggest extension methods to initialize the different connection strings. 现在,我不建议使用扩展方法来初始化不同的连接字符串。

Those I am sure are already coming from config but if not, and you are making a console rather than asp.net core app which makes configuration driven creation of DbContexts really easy I would really suggest learning how to use at least Microsoft.Extensions.Configuration to configure your DbContext instances from an appSettings. 我确信那些已经来自config,但是如果不是的话,您正在制作一个控制台而不是asp.net核心应用程序,这使得配置驱动的DbContexts的创建变得非常容易,我真的建议学习至少使用Microsoft.Extensions.Configuration从appSettings配置DbContext实例。

I can't share a code sample of initializing a DBContext with an DbOptionsBuilder directly because my guilty secret is I always get the DI in Asp.net Core to do it for me. 我不能直接使用DbOptionsBuilder分享初始化DBContext的代码示例,因为我的罪魁祸首是我总是在Asp.net Core中获得DI来为我做这件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架 .Net Core 3.1 - 代码优先与脚手架 - Entity Framework .Net Core 3.1 - Code First vs Scaffolding 带有 Entity Framework Core 的 SQLite 脚手架 - SQLite scaffolding with Entity Framework Core 实体框架核心 - 自定义脚手架 - Entity Framework Core - Customise Scaffolding 实体框架核心 - 脚手架枚举 - Entity framework Core - Scaffolding enum Entity Framework Core 自定义脚手架 - Entity Framework Core Customize Scaffolding 实体框架上下文和 model inheritance 在数据库第一种方法中搭建脚手架时 - Entity Framework context and model inheritance when scaffolding in database first approach 数据库优先错误实体框架.NET Core - Database First Error Entity Framework .NET Core 实体框架数据库 First.Net Core - Entity Framework Database First .Net Core ASP.NET 核心实体框架代码到数据库脚手架无法识别 Id 属性或 [Key] 注释 - ASP.NET Core Entity Framework code-to-database scaffolding not recognizing Id property or [Key] annotation 在实体框架(脚手架)中使用数据库优先方法时,是否忽略 HasKey.HasName("PK_123ABC")? - When using a database first approach in entity framework (scaffolding) Is the HasKey.HasName("PK_123ABC") ignored?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM