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

Question

I have an entity whose primary key is Guid and whose value is "Id"

public class FileStore
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Path { get; set; }
}

Further configuration

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<FileStore>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    base.OnModelCreating(modelBuilder);
}

I receive the following error while attempting to insert a record:

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 manually generate Guid. I simply want to put in a record and receiveId produced by the SQL Server. When I set.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) , Id In SQL Server, column is not an Identity column.

How can I set up Entity Framework in SQL Server to generate GUID automatically?

1
71
9/28/2015 11:08:19 PM

Popular Answer

You should also include the following properties in your Id column:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

When moving, you should modify yourCreateTable to includedefaultValueSQL to your column, such as:

Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),

You won't have to manually alter your database, which is something you want to avoid with Code First, as you said in the comments.

92
3/21/2018 12:05:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow