Can Entity Framework Core code migrations work reliably and practically against different database types

冷暖自知 提交于 2019-12-13 07:17:40

问题


I would like to clarify that this is the Core version Entity Framework that I'm working with.

I think I know the answer, but it's all based on assumptions from other ORMs I used years ago. My guess is the answer is something like "it depends based on the specific database(s) and the features used (keys, constraints, etc)".

Additionally, I want to clarify that I'm not asking if migrations can be generated from the model for different DBs. I know the answer is yes to that. I'm asking about a single set of already generated migrations.


回答1:


A single set of migrations can be applied to different database types. The tooling doesn't help much (issue #1825), so you may need to hand-edit the migration files.

Yes, it does depend on what features the databases support, so the path of least resistance is to use the lowest common set of features available across the providers. You can use annotations and the ActiveProvider property to influence provider-specific configuration. For example:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<int>(
        table: "Blogs",
        name: "Id",
        nullable: false)
        // Use AUTOINCREMENT on SQLite
        .Annotation("Autoincrement", true)
        // Use IDENTITY on SQL Server
        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

    if (ActiveProvider == "Microsoft.EntityFrameworkCore.SqlServer")
    {
        migrationBuilder.CreateSequence("SomeSequence");
    }
}


来源:https://stackoverflow.com/questions/39111308/can-entity-framework-core-code-migrations-work-reliably-and-practically-against

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!