ASP.Net Core - EntityFrameworkCore data is not adding, updating instead entity-framework entity-framework-core mysql


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; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Department { get; set; }
    public int Salary { get; set; }

I have configured fluent API in DBContext like this-

//Key automatic generation configuration
   .Property(b => b.Id)

And then calling from controller to add content like this-

Employee employee = new Employee
     City = newString,
     Department = newString,
     Name = newString,
     Salary = DateTime.UtcNow.Millisecond


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?


I have already tried-

public int Id { get; set; }

And [Key] public int Id { get; set; }


[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/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); }); ...

1/16/2018 12:15:21 PM

Related Questions


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