Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.2k views
in Technique[技术] by (71.8m points)

entity framework - EF Core always create .Annotation(“SqlServer:Identity”, “1, 1”) on add-migration .NET 5 /.NET CORE 5

<TargetFramework>net5.0</TargetFramework>

Entity

public class Country
{
    public long Id { get; set; }
    public string Name { get; set; } = null!;
    public string NationalityName { get; set; } = null!;
    public string PhonePrefix { get; set; } = null!;
    public string UnicodeFlag { get; set; } = null!;
    public bool Enabled { get; set; }
}

Configuration

public class CountryConfiguration : EntityTypeConfigurationBase<Country>
{
    public CountryConfiguration(DatabaseFacade database) : base(database)
    {
    }

    public override void Configure(EntityTypeBuilder<Country> builder)
    {
        builder.Property(e => e.Id);
        builder.Property(e => e.Name).IsUnicode().HasMaxLength(64);
        builder.Property(e => e.NationalityName).IsUnicode().HasMaxLength(64);
        builder.Property(e => e.PhonePrefix).HasMaxLength(20);
        builder.Property(e => e.UnicodeFlag).IsUnicode().HasMaxLength(4);
        builder.Property(e => e.Enabled);

        builder.HasKey(e => e.Id);
        builder.HasIndex(e => e.Name).IsUnique();
    }
}

Context

public class CoreDbContextBase : DbContext
{
    public DbSet<Country> Countries { get; set; } = null!;

    public CoreDbContextBase(DbContextOptions options):base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new CountryConfiguration(Database));           
    }
}

DbContext Factory

public class SqlServerDbContextFactory : IDesignTimeDbContextFactory<SqlServerDbContext>
{
    public SqlServerDbContext CreateDbContext(string[] args)
    {
        IConfiguration configuration = new ConfigurationBuilder().
                SetBasePath(Directory.GetCurrentDirectory())
                .AddUserSecrets<SqlServerDbContext>()
                .AddJsonFile(EntitiesConstants.DEFAULT_CONFIGURATION_FILE, false, true)
                .Build();
        DbSetting dbSetting = new DbSetting();
        configuration.Bind(nameof(DbSetting), dbSetting);

        DbContextOptions options = new DbContextOptionsBuilder<SqlServerDbContext>()
            .UseSqlServer(dbSetting.SqlServerConnectionString)
            .EnableSensitiveDataLogging(true).Options;

        return new SqlServerDbContext(options);
    }
}

The above code or Adding modelBuilder.UseIdentityColumns(); or modelBuilder.UseIdentityColumns(1, 1); in OnModelCreating or adding builder.Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(1,1); in configuration generates the following:

When add migration in my powershell script dotnet-ef migrations add "Migration_$($context)_$Guid" --startup-project "$StartupProject" --project "$Project" --context "$context" --output-dir "$outputDir" --verbose

1st migration is created without any problem. ??

public partial class Migration_SqlServerDbContext_b3e04304812f4d33ae7355317f325f44 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.EnsureSchema(
            name: "Base");

        migrationBuilder.CreateTable(
            name: "Country",
            schema: "Base",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                NationalityName = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                PhonePrefix = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                UnicodeFlag = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                Enabled = table.Column<bool>(type: "bit", nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("P_Country_Id", x => x.Id);
            });

        migrationBuilder.CreateIndex(
            name: "U_Country_Name",
            schema: "Base",
            table: "Country",
            column: "Name",
            unique: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Country",
            schema: "Base");
    }
}

2nd,3rd,4th..Nth migrations with any changes in my model creates the following ?

public partial class Migration_SqlServerDbContext_e07c05fcf33d40d7a1754255a7364121 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<long>(
            name: "Id",
            schema: "Base",
            table: "Country",
            type: "bigint",
            nullable: false,
            oldClrType: typeof(long),
            oldType: "bigint")
            .Annotation("SqlServer:Identity", "1, 1");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<long>(
            name: "Id",
            schema: "Base",
            table: "Country",
            type: "bigint",
            nullable: false,
            oldClrType: typeof(long),
            oldType: "bigint")
            .OldAnnotation("SqlServer:Identity", "1, 1");
    }
}

I tried this EF Core always create .Annotation("SqlServer:Identity", "1, 1"). But no result.

Try adding modelBuilder.UseIdentityColumns(2, 1); in OnModelCreating generates 1st migration with identity 1,1(bug??).

public partial class Migration_SqlServerDbContext_d5b7e1cf20914bf4acb8068c2c58c5be : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.EnsureSchema(
            name: "Base");

        migrationBuilder.CreateTable(
            name: "Country",
            schema: "Base",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"), //BUG?
                Name = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                NationalityName = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                PhonePrefix = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                UnicodeFlag = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                Enabled = table.Column<bool>(type: "bit", nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("P_Country_Id", x => x.Id);
            });

        migrationBuilder.CreateIndex(
            name: "U_Country_Name",
            schema: "Base",
            table: "Country",
            column: "Name",
            unique: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Country",
            schema: "Base");
    }
}

Try adding builder.Property(e => e.Id).ValueGeneratedOnAdd().UseIdentityColumn(2,1); resolves the problem the 1st migration is identity 2, 1. ??

public partial class Migration_SqlServerDbContext_c4823ca5280b4dda88c175f4e8a1a082 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.EnsureSchema(
            name: "Base");

        migrationBuilder.CreateTable(
            name: "Country",
            schema: "Base",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false)
                    .Annotation("SqlServer:Identity", "2, 1"), //OK
                Name = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                NationalityName = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
                PhonePrefix = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                UnicodeFlag = table.Column<string>(type: "nvarchar(4)", maxLength: 4, nullable: false),
                Enabled = table.Column<bool>(type: "bit", nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("P_Country_Id", x => x.Id);
            });

        migrationBuilder.CreateIndex(
            name: "U_Country_Name",
            schema: "Base",
            table: "Country",
            column: "Name",
            unique: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Country",
            schema: "Base");
    }
}

2nd,3rd,4th.... migrations are generated with empty actions in both cases. ??

public partial class Migration_SqlServerDbContext_e07c05fcf33d40d7a1754255a7364455 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
    }
}

References Project

<ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="5.0.0" />
    <PackageReference Include="Npgsql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...