2

I have a pretty standard situation that's been working however upon creating a new database and running (previously working) code, I get the following error:

Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF

I'm not specifying the ID.

This happens when I do the following:

var newFoo = new Foo{
    Name = "test"
}

db.Foos.Add(newFoo);
db.SaveChanges();

public class Foo {
  [Key]
  public int FooId {get; set;}
  public string Name {get; set;}
}

Why would this be happening?

stuartd
  • 70,509
  • 14
  • 132
  • 163
SB2055
  • 12,272
  • 32
  • 97
  • 202
  • are you using database first? – NtFreX Jun 27 '17 at 15:20
  • Does the set; argument not imply that the FooId will be set? Theoretically it would be passed as NULL? (sorry if this is not correct, I'm new to EF) – Jacob H Jun 27 '17 at 15:27
  • @NtFreX I am using code-first. – SB2055 Jun 27 '17 at 15:31
  • 2
    @JacobH no. This is standard practice. – SB2055 Jun 27 '17 at 15:32
  • Does the previously working code actually define the key like this? `[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]` – Crowcoder Jun 27 '17 at 15:43
  • @Crowcoder - no, I just have [Key] and this has automatically worked up until now. Do I need to specify that other attribute or is this an indication that something else is going on? I don't want to go trying things when auto-incrementing was working before, without understanding why it's no longer working. – SB2055 Jun 27 '17 at 15:47
  • 1
    I think you are going to have to try something since what you have is not working. I don't get to use EF much but I thought you had to tell it when a key is database generated. Maybe the other code set this via the fluent interface and you just didn't notice because that would likely be done in another file. – Crowcoder Jun 27 '17 at 15:51
  • According to [this](https://stackoverflow.com/questions/43112270/system-data-entity-infrastructure-dbupdateexception-error-even-when-i-am-not-upd?noredirect=1&lq=1) the accepted answer follows what Crowcoder commented about. – Charles May Jun 27 '17 at 16:45

0 Answers0