gpt4 book ai didi

c# - 防止在多对多表上按约定创建索引

转载 作者:行者123 更新时间:2023-11-29 03:18:56 24 4
gpt4 key购买 nike

在下面的配置中,EF 按照约定在 SyntaxId 上创建索引。由于我有一个复合主键(用作索引)并且没有标识列,因此我认为在多对多表中不需要在单个列上按约定创建的索引。

如何防止自动创建此约定索引 (b.HasIndex("SyntaxId");)?

public class SoftwareSyntaxTypeConfiguration : BaseJunctionTypeConfiguration<SoftwareSyntax>
{
public override void Configure(EntityTypeBuilder<SoftwareSyntax> entityTypeBuilder)
{
base.Configure(entityTypeBuilder);
entityTypeBuilder.ToTable("software_syntaxes");
entityTypeBuilder.HasKey(x => new {x.SoftwareId, x.SyntaxId});
entityTypeBuilder.HasOne(x => x.Software)
.WithMany(x => x.SoftwareSyntaxes)
.HasForeignKey(x => x.SoftwareId);
entityTypeBuilder.HasOne(x => x.Syntax)
.WithMany(x => x.SoftwareSyntaxes)
.HasForeignKey(x => x.SyntaxId);
}
}

partial class FilterListsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder.Entity("FilterLists.Data.Entities.Junctions.SoftwareSyntax", b =>
{
b.Property<int>("SoftwareId");

b.Property<int>("SyntaxId");

b.HasKey("SoftwareId", "SyntaxId");

b.HasIndex("SyntaxId"); //TODO: prevent this from being auto-created

b.ToTable("software_syntaxes");
});
}
}

更新添加实体类以进行说明。

public class Software
{
public int Id { get; set; }
public ICollection<SoftwareSyntax> SoftwareSyntaxes { get; set; }
...
}

public class Syntax
{
public int Id { get; set; }
public ICollection<SoftwareSyntax> SoftwareSyntaxes { get; set; }
...
}

public class SoftwareSyntax
{
public int SoftwareId { get; set; }
public Software Software { get; set; }

public int SyntaxId { get; set; }
public Syntax Syntax { get; set; }
}

最佳答案

事实证明,这是 not officially supported yet .

但是,解决方法是使用内部 EF API。它的使用需要注意,它可能会更改,恕不另行通知,因为它不适合外部使用。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
((Model)modelBuilder.Model).ConventionDispatcher.StartBatch();
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
foreach (var index in entityType.GetIndexes().ToList())
// if index is one you want to remove
entityType.RemoveIndex(index.Properties);
}

via Arthur Vickers

因为我的所有多对多实体都在同一个 Junctions 命名空间中,所以目前适用于我的实现是:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
((Model)modelBuilder.Model).ConventionDispatcher.StartBatch();
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
foreach (var index in entityType.GetIndexes().ToList())
if (index.DeclaringEntityType.Name.Contains("Junctions"))
entityType.RemoveIndex(index.Properties);
}

关于c# - 防止在多对多表上按约定创建索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com