2011-04-10 76 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)]