简体   繁体   English

以多对多关系定义FK名称

[英]Define FK names in many-to-many relationship

I what have many-to-many relationship between two entities. 我在两个实体之间有多对多的关系。 Everything works fine. 一切正常。 Is there a way to define names of FKs in intermediate table(StoresPushNotifications)? 有没有办法在中间表(StoresPushNotifications)中定义FK的名称?

The reason to ask is that mysql do not allow to define long constraint names. 要问的原因是mysql不允许定义长约束名称。 It generates random FK in case. 它会生成随机FK。 It breaks migration when I try to set migration to an earlier step. 当我尝试将迁移设置为较早的步骤时,它会中断迁移。

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

In my Context file, 在我的Context文件中,

modelBuilder.Entity<StoreEntity>()
    .HasMany<PushNotificationEntity>(s => s.PushNotifications)
    .WithMany(c => c.Stores)                
    .Map(cs =>
    {
        cs.MapLeftKey("StoreId");
        cs.MapRightKey("PushNotificationId");
        cs.ToTable("StoresPushNotifications");
    });

I had a similar problem and it was actually related to the migration key lengthrather than the foreign keys. 我有一个类似的问题,它实际上与迁移密钥长度相关而不是外键。

I resolved by modifying the migration configuration method to: 我通过将迁移配置方法修改为:

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

and then adding this method to limit the key lengths 然后添加此方法以限制密钥长度

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM