Cannot insert the value NULL into column in ASP.NET MVC Entity Framework

asp.net c# entity-framework

Question

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

1
17
5/23/2017 12:10:29 PM

Accepted Answer

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; }
    }
37
11/1/2013 1:28:22 PM

Popular Answer

I have encountered this problem multiple times while working with Microsoft SQL Server and I have followed the same way to fix it. To solve this problem, make sure Identity Specification is set to Yes. Here's how it looks like:

Identity Specification

In this way the column number auto increments as a primary key normally would.

HOW?: right-click the table that contains the column, choose Design, select the primary key and in Column Properties window find Identity Specification and set it to Yes.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow