我在两个实体之间有多对多的关系。一切正常。有没有办法在中间表中定义FK的名称(StoresPushNotifications)?
要问的原因是mysql不允许定义长约束名称。它会生成随机FK。当我尝试将迁移设置为较早的步骤时,它会中断迁移。
[Table("Stores")]
public class StoreEntity
{
[Key]
public int Id { get; set; }
public virtual ICollection<PushNotificationEntity> PushNotifications { get; set; }
}
[Table("PushNotifications")]
public class PushNotificationEntity
{
[Key]
public int Id { get; set; }
public ICollection<StoreEntity> Stores { get; set; }
}
在我的上下文文件中,
modelBuilder.Entity<StoreEntity>()
.HasMany<PushNotificationEntity>(s => s.PushNotifications)
.WithMany(c => c.Stores)
.Map(cs =>
{
cs.MapLeftKey("StoreId");
cs.MapRightKey("PushNotificationId");
cs.ToTable("StoresPushNotifications");
});
答案 0 :(得分:0)
我遇到了类似的问题,实际上它与迁移密钥的长度相关,而不是外键。
我通过将迁移配置方法修改为:
来解决internal sealed class Configuration : DbMigrationsConfiguration<CCDatabase.CCDbContext>
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations";
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
}
然后添加此方法以限制密钥长度
public class MySqlHistoryContext : HistoryContext
{
public MySqlHistoryContext(DbConnection connection, string defaultSchema) : base(connection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}