我试图连接一个一对多的关系,Workplace可以容纳多个人,而一个人只能有一个工作场所。
当我执行这段代码并检查结果时,p1已将w1正确分配为p1.Workplace,但是w1.employees列表总是为空。
即使在将w1分配给p1.Workplace后,我是否仍然需要手动将p1添加到w1.Employees中?
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": [
]
}
]
正如您所看到的,"employees"数组是空的,尽管p1应该在其中。