【问题标题】:Define FK names in many-to-many relationship在多对多关系中定义 FK 名称
【发布时间】:2017-05-07 19:44:27
【问题描述】:

我在两个实体之间具有多对多关系。一切正常。有没有办法在中间表(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");
    });

【问题讨论】:

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


    【解决方案1】:

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

    我通过修改迁移配置方式解决:

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

    【讨论】:

    • 是的,彼得,你提到的问题也在那里。但这里是 FK 长度。在这种情况下,当我回退到早期的迁移版本时,EF 无法在数据库的中间表中找到 FK。原因是数据库中 FK 的名称与 EF 查找的名称不同。如果我将“PushNotifications”表名更改为“PN”之类的名称,问题就消失了。
    • 和彼得为你的问题,按照这个,这个解决方案很简单。 stackoverflow.com/a/27082231/443389。谢谢
    • 谢谢,我使用的解决方案比此处链接的解决方案高出两个 - 我认为您的建议看起来更好。
    猜你喜欢
    • 2021-10-17
    • 2020-03-08
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多