使用 Entity Framework SqlException 插入数据库

INSERT into DB with Entity Framework SqlException

我正在通过 Entity Framework 将新实体插入数据库,设置所有属性,但代码仍然向我抛出带有文本的 SqlException:

Cannot insert the value NULL into column C_CUSTKEY, table y; column does not allow nulls.

但是我手动设置了所有属性,它们都不为空。什么会导致这个问题?

代码:

            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();

这是我的客户实体:

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

}

国家实体:

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

}

区域实体:

public class Region
{
    [Key]
    public int R_REGIONKEY { get; set; }

    public string R_NAME { get; set; }

    public string R_COMMENT { get; set; }

}

您更新了您的 EDMX 模型了吗?

如果没有,Entity Framework 无法知道您是否更改了数据库列属性。如果您打开您的模型并右键单击并选择 "Update Model From Database" 然后按 "Finish",它应该可以完成工作。

此外,您可以检查是否有一些主键未指定为数据库中的增量标识列,并且您没有在代码中设置任何值。

请按如下方式修饰 Customer 实体的主键 属性:

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