【问题标题】:EF Core Eager loading returns nullEF Core Eager 加载返回 null
【发布时间】:2021-01-31 22:17:28
【问题描述】:

我有一个实体患者和一个实体用户。它们之间是一对一的关系。

用户:

public class User
    {      
        public long Id { get; set; }

        public string Name { get; set; }

        public string Username { get; set; }      
                ......
        [JsonIgnore]
        public   Patient Patient { get; set; }
   }

患者:

public class Patient
    {
        public long Id { get; set; }

        public long UserId { get; set; }

        public  User User { get; set; }
    }

当我尝试从数据库中提取患者时,我得到了该用户的空引用。

DataContext:
 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Patient>()
                .HasOne(b => b.User)
                .WithOne(i => i.Patient)
                .HasForeignKey<Patient>(b => b.UserId);}

                 ....
    }

患者回购:

public IEnumerable<Patient> GetAll()
        {
            var patients = _dataContext.Patients.Include(x=>x.User);

            return patients;
        }

控制器方法:

  [HttpGet("patients")]
        public IActionResult GetAllPatient()
        {
            return Ok(_patientRepository.GetAll());
        }

迁移: 用户

migrationBuilder.CreateTable(
                name: "Users",
                columns: table => new
                {
                    Id = table.Column<long>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(nullable: true),
                    Username = table.Column<string>(nullable: true),
                    PasswordHash = table.Column<byte[]>(nullable: true),
                    PasswordSalt = table.Column<byte[]>(nullable: true),
                    BirthDate = table.Column<DateTime>(nullable: false),
                    GenderId = table.Column<int>(nullable: true),
                    UserRoleId = table.Column<long>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Users", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Users_Genders_GenderId",
                        column: x => x.GenderId,
                        principalTable: "Genders",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Users_UserRoles_UserRoleId",
                        column: x => x.UserRoleId,
                        principalTable: "UserRoles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

患者

migrationBuilder.CreateTable(
                name: "Patients",
                columns: table => new
                {
                    Id = table.Column<long>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    UserId = table.Column<long>(nullable: false),
                    DoctorId = table.Column<long>(nullable: true),
                    CaregiverId = table.Column<long>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Patients", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Patients_Caregivers_CaregiverId",
                        column: x => x.CaregiverId,
                        principalTable: "Caregivers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Patients_Doctors_DoctorId",
                        column: x => x.DoctorId,
                        principalTable: "Doctors",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_Patients_Users_UserId",
                        column: x => x.UserId,
                        principalTable: "Users",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

我在 Postman 上收到的信息:

 {
        "id": 1,
        "userId": 3,
        "user": null
}

调试时

我注意到一个奇怪的事情是 Mysql 将这种关系视为多对一

【问题讨论】:

标签: c# entity-framework asp.net-core .net-core


【解决方案1】:

在创建两个实体之间的关系时应该设置DeleteBehavior

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Patient>()
            .HasOne(b => b.User)
            .WithOne()
            .HasForeignKey<Patient>(b => b.UserId)
            .OnDelete(DeleteBehavior.Restrict);

}

【讨论】:

    【解决方案2】:

    显然有一些库为方法 .Include() 提供功能:Microsoft.EntityFrameworkCore(好的)System.Data.Entity(坏的);强> 我选择了坏的,我没有语法错误或运行时错误,只是功能不好。

    【讨论】:

      【解决方案3】:

      好的,您需要在查询中使用.ToList()

            var patients = _dataContext.Patients.Include(x=>x.User).ToList();
      

      【讨论】:

      • 我已经更改了它,我仍然收到 null。
      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      相关资源
      最近更新 更多