I have created a order entity and right now I have a Money type which I want to include it in my Order entity as an Own type.
public class Money
{
public decimal Value { get; set; }
public Currency Currency { get; set; }
}
and my Order class is like the following
public class Order
{
[Key]
public long OrderId { get; set; }
}
now I want to add a money type to order entity like the following:
public class Order
{
[Key]
public long OrderId { get; set; }
public Money Amount { get; set; }
}
and the OrderContext looks like the following:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().OwnsOne(o => o.Amount);
}
The issue happens when I run the entity framework migrations. This is what I get after running the migrations:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<long>(
name: "OrderId",
table: "Order",
nullable: false,
oldClrType: typeof(long),
oldType: "bigint")
.OldAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
migrationBuilder.AddColumn<int>(
name: "Amount_Currency",
table: "Order",
nullable: true);
migrationBuilder.AddColumn<decimal>(
name: "Amount_Value",
table: "Order",
nullable: true);
}
as you can see for some reason using OwnOne alters my OrderId column and when I check generated sql it looks like it drops the IDENTITY from it.
BEGIN
IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20200311224448_1.0.108-g5d3eec73db-Order') THEN
ALTER TABLE `Order` ALTER COLUMN "OrderId" TYPE bigint;
ALTER TABLE `Order` ALTER COLUMN "OrderId" SET NOT NULL;
ALTER TABLE `Order` ALTER COLUMN "OrderId" DROP IDENTITY;
ALTER TABLE `Order` ALTER COLUMN "OrderId" DROP DEFAULT;
END IF;
END $$;
DO $$
BEGIN
IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20200311224448_1.0.108-g5d3eec73db-Order') THEN
ALTER TABLE `Order` ADD "Amount_Currency" integer NULL;
END IF;
END $$;
DO $$
BEGIN
IF NOT EXISTS(SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20200311224448_1.0.108-g5d3eec73db-Order') THEN
ALTER TABLE `Order` ADD "Amount_Value" numeric NULL;
END IF;
END $$;
Does anybody know why adding an Owned type in Entity Framework and postgresql database causes this behavior and how can I make sure that the key field is not going to be altered?
- PostgreSQL 11.7
- Microsoft.AspNetCore.App 3.1.2
- Microsoft.NETCore.App 3.1.2
- Microsoft.EntityFrameworkCore.Design Version=3.1.1
- Npgsql.EntityFrameworkCore.PostgreSQL Version=3.1.2