2

Trying to insert a row into my database using Entity Framework. I assign all of the values upon insert except ID, which is the primary key, and I'd like it to get auto-incremented by the SQL Server DB.

My table definition/class:

public partial class T_SurfacePick
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public int? BoreholeID { get; set; }
    public int? AuthoredNameID { get; set; }
    public int? LoadFormat { get; set; }
    public double? PickDepth { get; set; }
    public int? OwningAuthorID { get; set; }
    public int? QualityID { get; set; }
    public double? CustomData { get; set; }
}

When I call the SaveChanges() method, I get an error

Cannot insert the value NULL into column 'ID'

How do I get this column to auto-increment itself? I'd like not to have to worry about keeping track of the ID and assigning it myself.

I'm trying to use the code-first approach. Here's an example of part of my decision tree for inserts/updates:

if (MenefeePick == null) // New top
{
   var Pick = new T_SurfacePick { BoreholeID = Wellbore.ID, AuthoredNameID = MenefeeAN.ID, LoadFormat = 1, PickDepth = Menefee, OwningAuthorID = ProgAuthor.ID, QualityID = -1, CustomData = null };
   db.T_SurfacePick.Add(Pick);
}
else // Update top
{
    MenefeePick.PickDepth = Menefee;
}
db.SaveChanges();

I'll further qualify by mentioning that my model uses an existing database from a software product.

John
  • 485
  • 3
  • 5
  • 16

2 Answers2

0

İf Model first try block

[Key]
 [DatabaseGenerated(DatabaseGeneratedOption.None)]
 public Int64 PolicyID { get; set; }
tayfun Kılıç
  • 2,042
  • 1
  • 14
  • 11
-3

Define ID as int? ID. With ? the variable will accept null.

i486
  • 6,491
  • 4
  • 24
  • 41
  • This is probably not what the op is looking for. Why would he want a null value as an id? – default Dec 18 '14 at 12:45
  • Don't know why, but the question is that "Cannot insert value NULL into column ID". – i486 Dec 18 '14 at 12:52
  • Please read the question again. The error message is *cannot insert value NULL*. The **question** is *How do I get this column to auto-increment itself?* – default Dec 18 '14 at 13:06
  • The code shows the column is the 'Key' but also Database Generated so maybe but a Zero in the ID column and let it get changed on INSERT –  Nov 17 '15 at 10:50