使用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; }
}
Country
和User
配置为:
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);
}
我能够创建迁移但是当我更新数据库时,我收到以下错误:
列“Countries.Code”与引用列“Users.CountryCode”是foreighn键“FK_User_Country_CountryCode”的长度或比例不同。参与外键关系的列必须以相同的长度和比例定义。无法创建约束或索引。
我能够解决错误,但只能删除.HasMaximumLength(2)
的{{1}}属性配置中的Country
,所以我最终得到了:
Code
如何使其工作但保持 builder.Entity<Country>().Property(x => x.Code).IsRequired().ValueGeneratedNever();
列长度等于2?
答案 0 :(得分:1)
您必须从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);
}