简体   繁体   中英

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

}

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.

Have you updated your EDMX model?

If you haven't, Entity Framework can't know if you have changed your database column attributes. If you open your model and right click and choose "Update Model From Database" and then press "Finish", it should do the work.

Also, you can check if you have some Primary Key that is not specified as a incremental identity column on the database, and you are not setting any value on your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM