0

I probably have spent 4 hours now and tried Code First approach and Database first approach

 db.MoveJobs.Add(moveJob);
 db.SaveChanges();

When a row is inserted it gives me

Cannot insert the value NULL into column 'id', table 'aspnet-AccountVerification.Web3.dbo.MoveJobs'; column does not allow nulls. INSERT fails. The statement has been terminated.

public class MoveJob
{
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }
        public string CountryCode { get; set; }
        public string PhoneNumber { get; set; }
}

Basically I need to generate incrementally a key for every itself for a new row. No Stack overflow / Forums / or something has helped.

I strangely worked yesterday though. I cant get where i went wrong

JJJ
  • 32,902
  • 20
  • 89
  • 102
Asad
  • 21,468
  • 17
  • 69
  • 94
  • That just means your `Id` column is not identity column in _database_. – Evk Mar 24 '18 at 14:51
  • it seems you are sending null for colum Id..can you check the data you are sending – user9405863 Mar 24 '18 at 14:51
  • I have made changes to Id column is as identity column. [id] INT NOT NULL IDENTITY, Im using local mdf file via server explorer. How can i make changes permanent / save ? – Asad Mar 24 '18 at 15:08
  • you don't need use `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]`. the property `id` by default is key and identity. first, remove this attribute and drop your database, after do this add a new migration. do you use fluent API? – Soheil Alizadeh Mar 24 '18 at 16:34
  • Possible duplicate of [Why is EF trying to insert NULL in id-column?](https://stackoverflow.com/questions/8855100/why-is-ef-trying-to-insert-null-in-id-column) – Soheil Alizadeh Mar 24 '18 at 16:36
  • which approach does this error come from? Your attempt seems to be a mix between code first and database first - you are trying code first, but your database does not match your model - as @Evk explained, is your property configured as identity, so EF won't pass the parameter as it suspects it to be computed by DBMS, while the database expects the value (the column is not Identity or at least not with a valid seed/inc) – DevilSuichiro Mar 25 '18 at 09:51

1 Answers1

0

You don't need use [DatabaseGenerated(DatabaseGeneratedOption.Identity)].

The property id by default is key and identity. First remove this attribute and drop your database, after do this add a new migration.

Soheil Alizadeh
  • 2,936
  • 11
  • 29
  • 56