首页 > 解决方案 > 为什么在 EF Core 中默认只为复合 PK 定义一个索引?

问题描述

我在实体框架核心(版本=3.1.5)中有这个模型。它表示节点和它们之间的链接,其中每个链接都有一个Parent节点和一个Children节点,每个节点有0-n个Children节点和0-n个Parent节点。

    public class GraphContext : DbContext
    {
        public DbSet<Node> Nodes { get; set; }
        public DbSet<Link> Links { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseSqlServer("cnxStr");

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Node>(n =>
            {
                n.Property(s => s.Id).ValueGeneratedOnAdd();
            });

            modelBuilder.Entity<Link>(l =>
            {
                l.HasKey(t => new { t.ParentId, t.ChildId });
                l.HasOne(ls => ls.Parent).WithMany(p => p.Children).HasForeignKey(ls =>  ls.ParentId ).OnDelete(DeleteBehavior.Restrict);
                l.HasOne(ls => ls.Child).WithMany(c => c.Parents).HasForeignKey(ls =>  ls.ChildId ).OnDelete(DeleteBehavior.Restrict);
                // l.HasIndex(d => d.ParentId);
            });
        }
    }

    public class Node
    {
        public Guid Id { get; set; }
        public List<Link> Parents { get; set; }
        public List<Link> Children { get; set; }
    }

    public class Link
    {
        public Guid ParentId { get; set; }
        public Node Parent { get; set; }
        public Guid ChildId { get; set; }
        public Node Child { get; set; }
    }

当我创建迁移时,默认包含以下索引:

migrationBuilder.CreateIndex(
    name: "IX_Links_ChildId",
    table: "Links",
    column: "ChildId");

但是,默认情况下不会为Link.ParentId. 为什么是一个而不是另一个?

备注:我可以添加l.HasIndex(d => d.ParentId);到模型配置中以使第二个索引出现。

标签: indexingentity-framework-coreone-to-onecomposite-key

解决方案


推荐阅读