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

c# entity-framework entity-framework-core

Question

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?

1
0
12/19/2015 4:00:33 PM

Accepted Answer

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

}
1
12/19/2015 4:00:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow