简体   繁体   中英

c# code first DB migration with stored proc versioning control

Our project is using EF code first approach, and it has quite a few stored proc.

Currently we generate DbMigration code like this

var scripts = StoredProcedureMigrationHelper.GetSqlBatchFromEmbeddedResource("myStoredProc.sql");
        foreach (var script in scripts)
        {
            Sql(script);
        }

The problem with this is that every time when I update the stored proc, I have to create new sql file, with name convention like "myStroedProc_versionX". Which is working but lose the version control benefit such as show the difference between versions.

Is there a way / different approach to update stored proc with version control in code first?

A more robust and flexible approach could be to use EF database first and to model your database using Sql Server Data Tools (SSDT). By creating Database project in your solution, you could build a dacpac and apply it on SQL Server instance to update your schema to the desired state.

Disclaimer: I'm a product manager at Redgate Software, makers of ReadyRoll

If you have Visual Studio 2017 Enterprise, which ships with ReadyRoll Core edition, you can switch to using SQL-based migrations for your database deployments. This would allow you to include the deployment of your stored procedures alongside your schema changes, while still allowing you to use EF CodeFirst to do your modelling.

You can read more about this approach in the ReadyRoll documentation: https://documentation.red-gate.com/display/RR1/Tutorial%3A+Entity+Framework+CodeFirst+migrations

Note that the article makes use of the programmable objects feature of ReadyRoll, which is only included in the Pro edition of ReadyRoll. As an alternative, you could script your stored procedures as post-deployment scripts (although this will cause the scripts to run with every deployment, rather than just on each change).

Unfortunately, EF doesn't provide a native solution for that, but I found a solution and I explain it in this post: https://softcadbury.github.io/dotnet/entity-framework/2022/05/10/versionize-stored-procedures-with-entity-framework.html

The idea is to embark the SQL code of your SQL stored procedures in your solution (works also with SQL views or SQL functions) and with a few C# extensions, you can manage them in EF migrations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM