1

When it comes to ASP Identity, I created a new table, custom table using code first and migration (code below). When I try to inset into that table using DbContext I have the id cannot be null error from entity framework. I tried using id with annotation as computed / identity and the error is the same.

For sure, I missed something but I cannot figure out what.

public class AspNetCountryTable
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public String Id { get; set; }
        public String CountryName { get; set; }
        public String CountryCode { get; set; }
    }

What I want to do is to have and automated generated Id (String) just the way asp identity is generating the id for the user.

Thanks!

  • Did you update your data base so that it actually generates an ID? – Fabiano Jun 20 '17 at 08:26
  • @Fabiano I used add-migration "new_migration_name" and update-database from package console to generate (in theory) the new sql table. Was there something else to do? – Iosif Bancioiu Jun 20 '17 at 08:28
  • Could you try with `[DatabaseGenerated(DatabaseGeneratedOption.None)]` instead of `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]`? – Keyur PATEL Jun 20 '17 at 08:33
  • String is a nullable type, hence it doesn't use computed values unlike `int` does when applying `DatabaseGeneratedOption.Identity` option. Try using `[DatabaseGenerated(DatabaseGeneratedOption.None)]` instead, or follow similar steps [here](https://stackoverflow.com/questions/36022901/how-can-i-change-an-int-id-column-to-guid-with-ef-migration) and [here](https://stackoverflow.com/questions/31926542/code-first-migration-from-int-to-guid-primary-key-issue) but instead of GUID it stores string. – Tetsuya Yamamoto Jun 20 '17 at 08:33
  • 5
    What do expect SQL to generate an identity column from `string`? – mshwf Jun 20 '17 at 08:39
  • did not work, changed at db level to uniqueidentifier and added addsequentialid() as default sql value – Iosif Bancioiu Jun 20 '17 at 10:26

1 Answers1

0

Had to add at SQL level Id column as uniqueidentifier instead of string and default sql value in migration script: newsequentialid()