I am inserting new entity into the DB through Entity Framework, setting all properties, but the code still throws me the SqlException with text:
Cannot insert the value NULL into column C_CUSTKEY, table y; column does not allow nulls.
But I manually set all properties, they are not null. What can cause this problem?
Code:
maxCustomerId = db.Customers.Max(o => o.C_CUSTKEY) + 1;
var customer = new Customer
{
C_CUSTKEY = maxCustomerId,
C_NATIONKEY = 1,
C_NAME = "Peter",
C_ADDRESS = "Praha",
C_COMMENT = "Best customer",
C_ACCTBAL = 0,
C_PHONE = "12345"
};
db.Customers.Add(customer);
db.SaveChanges();
This is my Customer entity:
public class Customer
{
[Key]
public int C_CUSTKEY { get; set; }
public string C_NAME { get; set; }
public string C_ADDRESS { get; set; }
public int C_NATIONKEY { get; set; }
[ForeignKey("C_NATIONKEY")]
public virtual Nation Nation { get; set; }
public string C_PHONE { get; set; }
public decimal C_ACCTBAL { get; set; }
public string C_COMMENT { get; set; }
}
Nation entity:
public class Nation
{
[Key]
public int N_NATIONKEY { get; set; }
public string N_NAME { get; set; }
public int N_REGIONKEY { get; set; }
[ForeignKey("N_REGIONKEY")]
public virtual Region Region { get; set; }
public string N_COMMENT { get; set; }
}
Region entity:
public class Region
{
[Key]
public int R_REGIONKEY { get; set; }
public string R_NAME { get; set; }
public string R_COMMENT { get; set; }
}
SELECT MAX(...) + 1to get your new unique primary key is horribly bad?? In a busy system with a few concurrent users, rather sooner than later, you'll have duplicate values - which is NOT a good thing for a primary key !