Autogenerate primary key (Guid) Entity Framework CTP5

百般思念 提交于 2020-01-24 21:33:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!