DatabaseGeneratedOption.Identity not generating an Id

asp.net-mvc c# entity-framework

Question

Using EntityFramework code-first, I've created a simple Foo table. Here's my entity:

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual string Id { get; set; }

    public virtual string Name { get; set; }
}

However whenever I try to insert a new row, I get a Cannot insert the value NULL into column 'Id'. Why is this happening when I've added a DatabaseGenerated attribute? Deleting and recreating my table makes no difference.

1
9
2/26/2014 7:01:41 AM

Accepted Answer

Identities for string column types are not supported with SQL Server. (How do you expect such a string to look like?) To get this working you could - for example - add a computed column/user defined function in SQL Server that formats a string from an ordinary int identity column - as shown here.

11
2/25/2014 11:07:02 PM

Popular Answer

  1. you forgot the Key attribute. and there is no need to use virtual for primary key.
  2. as mentioned by Slauma you can't use Identity for string datatype.

Try this code:

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

    public virtual string Name { get; set; }
}


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