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

前端 未结 3 1961
天命终不由人
天命终不由人 2020-12-31 03:32

When trying to use this code:

var model = new MasterEntities();

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

model.Customers.Add(customer);
         


        
相关标签:
3条回答
  • 2020-12-31 03:52

    You can configure SQL to auto-generate (and auto-increment) the primary key for the table upon inserts. Then just remove the [Key] in C# and you don't need to set the ID in the application manually, the db will generate it for you.

    0 讨论(0)
  • 2020-12-31 03:56

    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; }
        }
    
    0 讨论(0)
  • 2020-12-31 04:03

    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:

    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.

    0 讨论(0)
提交回复
热议问题