rish rish - 1 year ago 107
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-

public class Customer
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);
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";

I am using MySql Database, please someone help, thanks

Answer Source

You are probably assuming that by adding


... 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download