19

When trying to use this code:

var model = new MasterEntities();

var customer = new Customers();
customer.Sessionid = 25641;

model.Customers.Add(customer);
model.SaveChanges();

I get:

{"Cannot insert the value NULL into column 'Sessionid', table 'master.dbo.Column'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

The column "Sessionid" is actually the primary key and is marked with [KEY] like this:

 public class Customers
    {   
        [Key]
        public long Sessionid { get; set; }
        public long? Pers { get; set; }
    }

So according to this question, it seems as if when the property is marked with [KEY], EF ignores my own declaration of Sessionid since it expects the database to assign the value.

So how can I solve this? If I remove [KEY] I get the "entity type has no key defined" exception...

4

3 回答 3

38

I solved it by adding [DatabaseGenerated(DatabaseGeneratedOption.None)] like this:

public class Customers
    {   
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public long Sessionid { get; set; }
        public long? Pers { get; set; }
    }
于 2013-11-01T13:28:22.187 回答
2

您可以将 SQL 配置为在插入时自动生成(和自动递增)表的主键。然后只需删除 C# 中的 [Key],您无需在应用程序中手动设置 ID,db 将为您生成它。

于 2013-11-01T13:08:31.220 回答
2

我在使用时多次遇到此问题,Microsoft SQL Server并且我采用了相同的方法来解决它。要解决此问题,请确保将Identity Specification设置为Yes。这是它的样子:

身份规范

这样,列号会像主键一样自动递增。

HOW?: 右键单击包含该列的表,选择Design选择主键并在Column Properties窗口中找到Identity Specification并将其设置为Yes

于 2020-04-17T21:51:59.530 回答