c# - 在多对多关系中定义 FK 名称

标签 c# mysql entity-framework ef-code-first code-first

我在两个实体之间有多对多关系。一切正常。有没有办法在中间表(StoresPushNotifications)中定义 FK 的名称?

问的原因是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");
    });

最佳答案

我有类似的问题,它实际上与迁移 key 长度有关,而不是外键。

我通过将迁移配置方法修改为:

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

然后添加这个方法来限制 key 长度

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

关于c# - 在多对多关系中定义 FK 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278796/

相关文章:

php - 检查mysql用户是否存在

java - Android 使用 jdbc 连接到 google cloud sql

entity-framework - 使用 Entity Framework ,如何在多对多关系中向映射表添加记录

c# - 实体 VS 域模型 VS View 模型

c# - Entity Framework 数据库首先与 MySQL 不工作

c# - WinForms Designer 自动创建的事件处理程序

c# - 没有得到数据表对象的计数

c# - 如何使用 ListView /组合框 uwp 设置默认选定项

c# - 使用异步等待的并行多线程下载

php - 将 mysql_query() 的结果插入到同一个数据库中