I am using EF Core 5 with SQL Server and I have following simple entity:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
}
which is added in DbContext as:
public DbSet<Person> People { get; set; }
I run add-migration Person
get following generated migration code:
public partial class Person : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "People",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_People", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "People");
}
}
Then I run update-database
to create this Person
table in the database.
context.People.Add(new Person() { Name = "John" });
context.SaveChanges();
Looking in the EF log I see SQL command executed:
Executed DbCommand (21ms) [Parameters=[@p0='115b2a5d-56b7-42c8-2f42-08d8cd03a34e', @p1='John' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [People] ([Id], [Name])
VALUES (@p0, @p1);
I notice the first parameter for Id is @p0='115b2a5d-56b7-42c8-2f42-08d8cd03a34e'
so this means that Guid is generated by EF and not by database. I want it to be generated by the database.
So I add following attributes to the Id
property:
public class Person
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
}
But when I create a new migration it gives me empty Up()
and Down()
methods which means from the EF perspective nothing should be changed in the database. Why is this? And how can I make EF Core 5 create Id
primary key auto generated by database.