Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls
c#, entity-framework, entity-framework-6, sql-server-2008
Solution
In addition to adding these attributes to your Id column:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
in your migration you should change your `CreateTable` to add the `defaultValueSQL` property to your column i.e.:
Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),
This will prevent you from having to manually touch your database which, as you pointed out in the comments, is something you want to avoid with Code First.
Problem
I have an entity with primary key "Id" which is Guid: ``` public class FileStore { public Guid Id { get; set; } public string Name { get; set; } public string Path { get; set; } } ``` And some configuration: ``` protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<FileStore>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); base.OnModelCreating(modelBuilder); } ``` When I try to insert a record I get a following error: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated. I don't want to generate Guid manually. I just want to insert a record and get `Id` generated by SQL Server. If I set `.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)`, `Id` column is not Identity column in SQL Server. How can I configure Entity Framework to autogenerate Guid in SQL Server?