0

當我在Azure .Net後端製作遷移文件時,它會自動生成五個必填字段(Id,CreatedAt,UpdatedAt,Version,Deleted)和我的客戶字段。它將Id定義爲主鍵。更改EF6中的主鍵名稱

public override void Up() 
    { 
     CreateTable(
      "dbo.People", 
      c => new 
       { 
        Id = c.String(nullable: false, maxLength: 128, 
         annotations: new Dictionary<string, AnnotationValues> 
         { 
          { 
           "ServiceTableColumn", 
           new AnnotationValues(oldValue: null, newValue: "Id") 
          }, 
         }), 
        PersonType = c.String(nullable: false, maxLength: 2), 
        FirstName = c.String(nullable: false, maxLength: 50), 
        MiddleName = c.String(maxLength: 50), 
        LastName = c.String(nullable: false, maxLength: 50), 
        Gender = c.String(nullable: false, maxLength: 1), 
        BirthDate = c.DateTime(nullable: false, storeType: "date"), 
        Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion", 
         annotations: new Dictionary<string, AnnotationValues> 
         { 
          { 
           "ServiceTableColumn", 
           new AnnotationValues(oldValue: null, newValue: "Version") 
          }, 
         }), 
        CreatedAt = c.DateTimeOffset(nullable: false, precision: 7, 
         annotations: new Dictionary<string, AnnotationValues> 
         { 
          { 
           "ServiceTableColumn", 
           new AnnotationValues(oldValue: null, newValue: "CreatedAt") 
          }, 
         }), 
        UpdatedAt = c.DateTimeOffset(precision: 7, 
         annotations: new Dictionary<string, AnnotationValues> 
         { 
          { 
           "ServiceTableColumn", 
           new AnnotationValues(oldValue: null, newValue: "UpdatedAt") 
          }, 
         }), 
        Deleted = c.Boolean(nullable: false, 
         annotations: new Dictionary<string, AnnotationValues> 
         { 
          { 
           "ServiceTableColumn", 
           new AnnotationValues(oldValue: null, newValue: "Deleted") 
          }, 
         }), 
       }) 
      .PrimaryKey(t => t.Id) 
      .Index(t => t.CreatedAt, clustered: true); 

    } 

我想這個主鍵名「ID」更改爲「PERSONID」,所以我添加主鍵屬性像下面

public class Person : EntityData 
{ 
    public string PersonId; 
    .... 
} 

但沒有奏效。 「Id」未被「PersonId」取代,只是作爲客戶字段添加到遷移文件中。所以,增加了[Key]屬性,但是出錯了,我得到了下面的消息。 「

」無法確定類型的組合主鍵排序。使用ColumnAttribute或HasKey方法指定組合主鍵的順序。

如何更改主鍵名稱?

+0

您應該爲重命名的列手動添加遷移代碼。 –

回答

1

您可以使用HasKey方法將該屬性設置爲主鍵。

例如,

modelBuilder.Entity<Person>().HasKey(t => t.PersonId); 

它將設置PERSONID作爲主鍵。

祝你好運。