ASP.Net Core - EntityFrameworkCore data is not adding, updating instead

asp.net asp.net-core-2.0 entity-framework entity-framework-core mysql

Question

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.

1
1
1/17/2018 4:00:50 AM

Popular Answer

you are mixing data annotations and fluent api configurations which is not a good practice. anyway, entity framework considers int Id in persistence models as key in general so you don't have to specify it manually. I recommend you choosing only one approach (from my experience fluent api is usually better - more extensible for future and persistence models look much cleaner) and try to go without specifying that the Id should or should not change because without it you will get what you want.

your migration should look like this:

migrationBuilder.CreateTable( name: "TableName", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn) }, constraints: table => { table.PrimaryKey("PK_TableName", x => x.Id); }); ...

0
1/16/2018 12:15:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow