一对多返回空数组(已解决) [英] One To Many returns empty array (solved)

查看:94
本文介绍了一对多返回空数组(已解决)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以一对多关系连接两个对象,Workplace可以容纳多个People,而一个Person只能拥有一个Workplace.

I'm trying to connect two objects with one-to-many relationship, Workplace can hold multiple People, while one Person can only have one Workplace.

当我执行此代码片段并检查结果时,p1已将w1正确分配为p1.Workplace,但是w1.employees的人员列表始终为空.

When I execute this code snippet and check to see the results, p1 has properly assigned w1 as the p1.Workplace, but the list of people of the w1.employees is always empty.

即使我将w1分配给p1.Workplace,我是否仍必须手动将p1添加到w1.Employees?

Do I have to manually add p1 to w1.Employees even after I assigned w1 to p1.Workplace?

SeedData.cs (代码段)

var w1 = new Workplace
{
   EntryCode = "1111"
   //[...] other data I cut out for brievity
};
context.Workplaces.Add(w1);

Person p1 = new Person
{
    Name = "Spencer",
    Workplace = w1
   //[...] other data I cut out for brievity
};
context.Person.Add(p1)
context.SaveChanges();

Workplace.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Counsel.Models
{
    [Table("Workplace")]
    public class Workplace
    {
        [Column("WorkplaceId")]
        public int WorkplaceId {get;set;}

        [Column("EntryCode")]
        public string EntryCode {get;set;}

        [Column("ConfirmationCode")]
        public string ConfirmationCode {get;set;}

        [Column("Employees")]
        public ICollection<Person> Employees {get;set;}
    }
}

Person.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Counsel.Models
{
    public class Person
    {
        [Column("PersonId")]
        public int PersonId {get;set;}

        [Column("Image")]
        public string Image {get;set;}

        [Column("FName")]
        public string FName { get; set; }

        [Column("LName")]
        public string LName {get;set;}

        [Column("Role")]
        public string Role {get;set;}

        [Column("Email")]
        public string Email {get;set;}

        [Column("Password")]
        public string Password {get;set;}

        public Workplace Workplace {get;set;} = new Workplace();
        public ICollection<ChatPerson> Chats {get;set;}
    }
}

DataContext.cs

using Counsel.Models;
using Microsoft.EntityFrameworkCore;

namespace Counsel.Models {
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> opts): base(opts){}

        public DbSet<Person> People {get;set;}
        public DbSet<Workplace> Workplaces {get;set;}


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Person>((item)=>{
                item.HasKey(p => p.PersonId);
                item.HasOne<Workplace>(p => p.Workplace).WithMany(w => w.Employees).OnDelete(DeleteBehavior.SetNull);
            });


            modelBuilder.Entity<Workplace>((item)=>{
                item.HasKey(p => p.WorkplaceId);
                item.HasMany<Person>(w => w.Employees).WithOne(p => p.Workplace).OnDelete(DeleteBehavior.Cascade);
            });
        }
    }
}

WorkplaceController.cs (代码段)

[HttpGet("{id}")]
        public Workplace GetWorkplace(int id)
        {
           return context.Workplaces
                .Where(c => c.WorkplaceId == id)
                .Include(c => c.Employees).ThenInclude(c => c.Workplace)
                .FirstOrDefault();

        }

GetWorplace()输出

[
  {
    "workplaceId": 1,
    "entryCode": "1111",
    "confirmationCode": "1111",
    "employees": [

    ]
  }
]

如您所见,即使p1应该存在,员工"数组也为空.

As you can see, the "employees" array is empty, even though p1 should be there.

推荐答案

问题是由引用导航属性初始值设定项引起的:

The problem is caused by the reference navigation property initializer:

public Workplace Workplace { get; set; } = new Workplace(); // <--

从不执行此操作-混淆EF导航属性修复并导致意外的运行时行为.

Never do that - it confuses EF navigation property fixup and leads to unexpected runtime behaviors.

请注意,初始化 collection 导航属性是可以的,尽管不是必需的.这是因为参考导航属性中的null具有特殊含义,并且确实提供了指向主体实体的链接,该主体实体可能包含也可能不包含从属实体的集合.

Note that initializing collection navigation properties is ok, although not required. It's because null in reference navigation property have a special meaning and really provides a link to the principal entity, which may or may not contain collection of dependent entities.

很快,删除初始化程序

public Workplace Workplace { get; set; }

问题将得到解决.

这篇关于一对多返回空数组(已解决)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆