列...與引用列的長度或比例不同


使用Entity Framework 7,我有以下實體:

public class Country {
  public String Code { get; set; }
  public String Name { get; set; }
  public virtual ICollection<User> Users { get; set; }    
}

public class User : IdentityUser<Int32> {   
  public String CountryCode { get; set; }
  public virtual Country Country { get; set; }
}

CountryUser配置是:

public class Country {
  public String Code { get; set; }
  public String Name { get; set; }
  public virtual ICollection<User> Users { get; set; }    
}

public class User : IdentityUser<Int32> {   
  public String CountryCode { get; set; }
  public virtual Country Country { get; set; }
}

我能夠創建遷移但是當我更新數據庫時,我收到以下錯誤:

列“Countries.Code”與引用列“Users.CountryCode”是foreighn鍵“FK_User_Country_CountryCode”的長度或比例不同。參與外鍵關係的列必須以相同的長度和比例定義。無法創建約束或索引。

我能夠解決錯誤,但只能在CountryCode屬性配置中刪除.HasMaximumLength(2) ,所以我最終得到:

public class Country {
  public String Code { get; set; }
  public String Name { get; set; }
  public virtual ICollection<User> Users { get; set; }    
}

public class User : IdentityUser<Int32> {   
  public String CountryCode { get; set; }
  public virtual Country Country { get; set; }
}

如何使其工作但保持Code列長度等於2?

一般承認的答案

您必須從User實體配置CountryCode屬性,如下所示:

protected override void OnModelCreating(ModelBuilder builder) 
{
    base.OnModelCreating(builder);

    builder.Entity<Country>().ToTable("Countries");
    builder.Entity<Country>().HasKey(x => x.Code);
    builder.Entity<Country>().Property(x => x.Code).IsRequired().HasMaximumLength(2).ValueGeneratedNever();
    builder.Entity<Country>().Property(x => x.Name).IsRequired().HasMaxLength(80);        

    builder.Entity<User>().ToTable("User");
    builder.Entity<User>().HasKey(x => x.CountryCode);
    builder.Entity<User>().Property(x => x.CountryCode).IsRequired().HasMaximumLength(2).ValueGeneratedNever();
    builder.Entity<User>()
        .HasOne(x => x.Country)
        .WithMany(x => x.Users)
        .HasForeignKey(x => x.CountryCode);

}




許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因