Search code examples
c#entity-frameworkef-code-firstsqlexception

INSERT into DB with Entity Framework SqlException


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; }

}

Solution

  • Please decorate your primary key property of Customer entity as follows:

     [DataMember, Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
     public int C_CUSTKEY { get; set; }
    

    The key here is putting the attributes:

    1. Key
    2. DatabaseGenerated

    onto the C_CUSTKEY column. Apparently the issue we are fighting is that Entity Framework by default expects to do inserts with keys being identities.