Miguel Moura
Miguel Moura

Reputation: 39474

Column ... is not the same length or scale as referencing column

With Entity Framework 7 I have the following entities:

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

And Country and User configurations are:

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<Country>().ToTable("Users");

  builder.Entity<Country>()
    .HasOne(x => x.Country)
    .WithMany(x => x.Users)
    .HasForeignKey(x => x.CountryCode);
}

I am able to create the migration but when I update the database I get the following error:

Column "Countries.Code" is not the same length or scale as referencing column "Users.CountryCode" is foreighn key "FK_User_Country_CountryCode". Columns participating in a foreign key relationship must be defined with the same length and scale. Could not create constraint or index.

I was able to solve the error but only by removing .HasMaximumLength(2) in Country's Code property configuration so I ended up with:

  builder.Entity<Country>().Property(x => x.Code).IsRequired().ValueGeneratedNever();

How can I make it work but keeping the Code column length equal to 2?

Upvotes: 0

Views: 2295

Answers (1)

Alberto Monteiro
Alberto Monteiro

Reputation: 6229

You must configure CountryCode property from User entity like that:

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

}

Upvotes: 1

Related Questions