创建迁移时,如何防止 Entity Framework Core 7 将外键字段添加到引用同一类的某个类?

问题描述 投票:0回答:1

感谢您阅读本文。我对 Entity Framework Core 有点陌生,我正在尝试使用代码优先原则来创建应该创建我的数据库的迁移。

但我偶然发现了一些意想不到的行为,至少在我看来是这样。也许有人好心帮助我,我可能做错了什么。

我创建了一个具有以下属性的示例项目:

  1. VS2022社区(64位)版本17.6.5
  2. C# (.NET 6.0)
  3. Entity Framework Core 7.0.10(我使用
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Design
    Microsoft.EntityFrameworkCore.SqlServer
    Microsoft.EntityFrameworkCore.Tools
    包)

目标数据库是SQL Server。

我创建了一个类

SampleEntity
,如下:

namespace Model.SampleEntitySet
{
    public class SampleEntity : SampleEntities
    {
        public Guid Id { get; set; }
        public string Description { get; set; } = string.Empty;
    }
}

SampleEntities 定义如下:

using Microsoft.EntityFrameworkCore;
using Model.SampleEntitySet;

namespace Model
{
    public class SampleEntities : DbContext
    {
        public DbSet<SampleEntity> SampleEntitySet { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Something");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<SampleEntity>(entity =>
            {
                entity.HasKey(e => e.Id); // Configure primary key
            });
        }
    }
}

当我创建迁移时,我使用以下命令:

dotnet ef migrations add InitialCreate --context SampleEntities

然后创建以下迁移:

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Model.Migrations
{
    /// <inheritdoc />
    public partial class InitialCreate : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "SampleEntitySet",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    SampleEntityId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_SampleEntitySet", x => x.Id);
                    table.ForeignKey(
                        name: "FK_SampleEntitySet_SampleEntitySet_SampleEntityId",
                        column: x => x.SampleEntityId,
                        principalTable: "SampleEntitySet",
                        principalColumn: "Id");
                });

            migrationBuilder.CreateIndex(
                name: "IX_SampleEntitySet_SampleEntityId",
                table: "SampleEntitySet",
                column: "SampleEntityId");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "SampleEntitySet");
        }
    }
}

快照包含:

// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

#nullable disable

namespace Model.Migrations
{
    [DbContext(typeof(SampleEntities))]
    partial class SampleEntitiesModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "7.0.10")
                .HasAnnotation("Relational:MaxIdentifierLength", 128);

            SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);

            modelBuilder.Entity("Model.SampleEntitySet.SampleEntity", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uniqueidentifier");

                    b.Property<string>("Description")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<Guid?>("SampleEntityId")
                        .HasColumnType("uniqueidentifier");

                    b.HasKey("Id");

                    b.HasIndex("SampleEntityId");

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

            modelBuilder.Entity("Model.SampleEntitySet.SampleEntity", b =>
                {
                    b.HasOne("Model.SampleEntitySet.SampleEntity", null)
                        .WithMany("SampleEntitySet")
                        .HasForeignKey("SampleEntityId");
                });

            modelBuilder.Entity("Model.SampleEntitySet.SampleEntity", b =>
                {
                    b.Navigation("SampleEntitySet");
                });
#pragma warning restore 612, 618
        }
    }
}

请注意,SampleEntityId 作为实体被创建为可为空的 Guid 和外键 FK_SampleEntitySet_SampleEntitySet_SampleEntityId。

我在网上搜索以了解为什么会发生这种情况,但到目前为止我还没有找到解决方案。 我知道我可以手动删除额外的字段和外键及其索引。但我根本不想创建它们。这对我来说没有意义。

c# entity-framework entity-framework-migrations
1个回答
0
投票

为什么你的实体类(SampleEntity)继承了你继承的类 数据库上下文?我相信要解决您的问题,您只需将

public class SampleEntity : SampleEntities
更改为
public class SampleEntity

查看此文档:https://learn.microsoft.com/en-us/ef/core/modeling/

© www.soinside.com 2019 - 2024. All rights reserved.