问题
I have a following POCO class
public class Account
{
[Key,DatabaseGenerated(DatabaseGenerationOption.Identity)]
public string AccountId { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Email { set; get; }
}
I get the following exception when the database gets created
Identity column 'AccountId' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.
回答1:
Shouldn't you have:
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid AccountId { set; get; }
?
回答2:
Jeff's answer is right. Just a little tip for you. Using EF6 I wrote next configuration in order to set all fields with name "Id" and type "Guid" as identity.
modelBuilder.Properties<Guid>()
.Where(info => info.Name.ToLower()== "id")
.Configure(configuration => configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
So I don't have to write [DatabaseGenerated(DatabaseGenerationOption.Identity)]
everytime.
回答3:
Sound like you have to update your AccountId property from string to one of the mentioned datatypes in the exception:
int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable
Any reason why it's now a string?
来源:https://stackoverflow.com/questions/5610794/autogenerate-primary-key-guid-entity-framework-ctp5