Стремительная загрузка для отношений один к одному в EF Core - PullRequest
0 голосов
/ 29 апреля 2020

Кто-нибудь знает, есть ли проблема с отношением один к одному в 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 Загрузка:

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

Но когда я использую Готовая загрузка ничего не возвращает.

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

Протестировано с почтальоном:

https://localhost:44355/api/authors

для: вернуть контекст ожидания .Authors.ToListAsyn c ();
It возвращает:

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

для: вернуть контекст ожидания .Authors.Include (a => a.Biography) .ToListAsyn c ();
Возвращает:

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
...