首页 > 解决方案 > EF Core 中一对一关系的急切加载

问题描述

有谁知道 EF Core 和 Eager Loading 中的一对一关系是否存在问题,或者问题是我知之甚少?

例如,如果我有这样一个简单的一对一关系:

    public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Biography Biography { get; set; }
    }



    public class Biography
    {
        public int Id { get; set; }
        public string BiographyResume { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string PlaceOfBirth { get; set; }
        public string Nationality { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

    public class OneDbContext : DbContext
    {
        public DbSet<Author> Authors { get; set; }


        public OneDbContext(DbContextOptions<OneDbContext> options)
            : base(options)
        {

        }
    }

这是迁移:

    public partial class CreateAuthorsTable : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Authors",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    FirstName = table.Column<string>(nullable: true),
                    LastName = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Authors", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Biography",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    BiographyResume = table.Column<string>(nullable: true),
                    DateOfBirth = table.Column<DateTime>(nullable: false),
                    PlaceOfBirth = table.Column<string>(nullable: true),
                    Nationality = table.Column<string>(nullable: true),
                    AuthorId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Biography", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Biography_Authors_AuthorId",
                        column: x => x.AuthorId,
                        principalTable: "Authors",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Biography_AuthorId",
                table: "Biography",
                column: "AuthorId",
                unique: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Biography");

            migrationBuilder.DropTable(
                name: "Authors");
        }
    }

现在,在 Controller 中,没有 Eager Loading 一切都很好:

    [Route("api/[controller]")]
    public class AuthorsController : Controller
    {
        private readonly OneDbContext context;

        public AuthorsController(OneDbContext context)
        {
            this.context = context;
        }

        [HttpGet]
        public async Task<IEnumerable<Author>> GetAuthors()
        {
            return await context.Authors.ToListAsync();
        }
    }

但是当我使用 Eager Loading 时,它不会返回任何内容。

        [HttpGet]
        public async Task<IEnumerable<Author>> GetAuthors()
        {
            return await context.Authors.Include(a => a.Biography).ToListAsync();
        }

用邮递员测试:

https://localhost:44355/api/authors

for:返回等待 context.Authors.ToListAsync();
它返回:

[
    {
        "id": 1,
        "firstName": "Luka",
        "lastName": "Jovic",
        "biography": null
    },
    {
        "id": 2,
        "firstName": "Stefan",
        "lastName": "Savic",
        "biography": null
    }
]

for:返回等待 context.Authors.Include(a => a.Biography).ToListAsync();
它返回:

Could not get any response
There was an error connecting to https://localhost:44355/api/authors.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

标签: entity-framework-coreeager-loading

解决方案


推荐阅读