I am using ASP.Net Core 2 and Entity Framework Core with MySQL.
I want to add a simple entity to the database.
My Model is like this-
public class Employee
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string City { get; set; }
[Required]
public string Department { get; set; }
[Required]
public int Salary { get; set; }
}
I have configured fluent API in DBContext like this-
//Key automatic generation configuration
modelBuilder.Entity<Employee>()
.Property(b => b.Id)
.ValueGeneratedOnAdd();
And then calling from controller to add content like this-
Employee employee = new Employee
{
City = newString,
Department = newString,
Name = newString,
Salary = DateTime.UtcNow.Millisecond
};
_context.Employee.Add(employee);
_context.SaveChanges();
What I am seeing is updating the first data having ID = 1 and never add new data. I want my ID to be auto-incrementing and don't want to use GUID for maintaining ID. What do I need to do to make it work?
Update-
I have already tried-
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
And [Key] public int Id { get; set; }
And
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
But no luck.
The complete code is in this Github Repository.
And the controller is here.
Add
should not generateUPDATE
, turn on EF Core logging and take a look at the executed commands.