2011-04-10 69 views
1

我有以下POCO类自动生成主键(GUID)实体框架CTP5

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; } 


    } 

我得到下面的异常当数据库被创建

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. 
+0

注意:如果您在模型类中使用“保留”标识列名称“Id”,即使您有'[Key,DatabaseGenerated(...)]' - 也必须重新命名把你的模型中的你的身份财产转移到别的东西上,比如在这种情况下,'AccountId'。 – rdev5 2016-09-22 20:11:22

回答

8

你不应该有:

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

+0

正是...我已经错误地键入字符串...只要我改变它为Guid它工作....谢谢 – 2011-04-10 09:55:12

0

听起来像是你需要更新您的帐户ID属性从字符串到异常中提到的数据类型之一:

int,bigint,smallint,tinyint或小数或数字,刻度为0,并且约束为nonnulla ble

为什么现在是字符串?

+0

没有什么特别的理由....这是一个错误... – 2011-04-10 09:55:44

3

杰夫的回答是对的。只是给你一点小费。使用EF6我写了下一个配置,以便设置名称为“Id”并键入“Guid”作为标识的所有字段。

modelBuilder.Properties<Guid>() 
      .Where(info => info.Name.ToLower()== "id") 
      .Configure(configuration => configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)); 

所以我不必每次都写[DatabaseGenerated(DatabaseGenerationOption.Identity)]