rish rish - 3 months ago 16
MySQL Question

Primary Key Always Inserting Zero

I just started learning Entity Framework and I am trying to insert data into data base. I have Customer table which has three fields id(int), name(varchar) and address(varchar). When I am trying to insert data into database every time ID is inserted as 0 value.

My Customer Class-

[Table("customer")]
public class Customer
{
[Key]
[Column("custId")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int custId { get; set; }
public string name { get; set; }
public string address { get; set; }
}


And My Insert Methods-

static void insertCustomer(Customer cust)
{
using(var context = new DBEntities())
{
Console.WriteLine("ID: " + cust.custId);
context.customer.Add(cust);
context.SaveChanges();
Console.WriteLine("Customer Inserted Successfully!!!");
}
}


And I am calling Insert method like this

Customer cust = new Customer();
cust.custId = 106;
cust.name = "Prince";
cust.address = "Kolkata";
insertCustomer(cust);


I am using MySql Database, please someone help, thanks

Answer

You are probably assuming that by adding

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

... on a property, that it tells EF to automatically populate the value. But that's not the case.

It's actually the other way around. By decorating a property with that attribute, you are telling EF that it doesn't need to validate or worry about that value, and that the database will take care of populating it with an auto-incrementing value.

However, this relies on you having defined the database table correctly to produce that behavior. It doesn't happen automatically. You need to make sure that your MySQL table has the column defined correctly as AUTO_INCREMENT.