微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 以多对多关系定义FK名称

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

在我的Context文件中,

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

解决方法

我有一个类似的问题,它实际上与迁移密钥长度相关而不是外键.

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐