加载子对象的集合,覆盖单个子对象(这是延迟加载问题吗?)

Collections of child objects are loaded, single child objects are overwritten (is this a lazy-loading issue?)

我正在使用 EF Core 5.08(Blazor 服务器应用程序)。

我有一个 class Assignment 具有以下属性:

public Guid AssignmentId { get; set;    
public Guid AssetId { get; set; }
public virtual Asset Asset { get; set; }
public virtual List<Person> People { get; set }

public Assignment(){ 
     this.AssignmentId = Guid.NewGuid();
     this.Asset = new Asset();
     this.People = new List<Person>();
}

class Asset:

public Guid AssetId { get; set; }    
public virtual List<Assignment> Assignments

public Asset() {
     this.AssetId = Guid.NewGuid();
     this.Assignments = new List<Assignment>();
}

AssignmentPerson是多对多的关系。 AssetAssignment 具有一对多关系(即每个 Assignment 引用一个 Asset 而每个 Asset 引用一个 Assignments 的集合)。

Entity Framework 创建连接 table AssignmentPerson;这个,加上启用的延迟加载,我可以访问和呈现剃须刀组件中 Assignment.People 的属性。

在 razor 组件中,当我访问 Assignment.AssetId 时,外键如预期的那样(即它是数据库中相应 Asset 的主键)。

奇怪的是,当我访问和呈现 Assignment.Asset.AssetId 时,Asset 主键不是外键 (Assignment.AssetId);似乎构建了一个新的 Asset 而不是我预期的 Asset

我认为它与延迟加载有关。怎么可能外键是正确的,但是Assignment.Asset被覆盖了?

为了在 razor 组件中获取 Assignments,我注入了我的服务 AssignmentService 并调用它的方法:

    public List<Assignment> Get(Guid workspaceId)
    {
        Workspace workspace = context.Workspaces.Find(workspaceId);
        return workspace.Assignments;
    }

    public Task<List<Assignment>> GetAsync(Guid workspaceId)
    {
        return Task.Run(() => this.Get(workspaceId));
    }

     protected override async Task OnInitializedAsync()
     {
          this.assignments = await assignmentService.GetAsync(Guid.Parse("//The Workspace.Guid"));
     }

不应该有任何延迟加载。我不确定 Find() 的作用,但试试这个:

public List<Assignment> Get(Guid workspaceId)
{
    Workspace workspace = context
      .Workspaces
      .Include(ws => ws.Assignments).ThenInclude(a => a.Asset)
      .SingleOrDefault(ws => ws.WorkspaceId == workspaceId);
    return workspace.Assignments;
}

此外,Db应该生成一个Id,EF将default(Guid)识别为NULL。所以,

  //this.AssetId = Guid.NewGuid();  -- don't do this

并且赋值构造函数应该初始化资产属性。

初始化 List<> 属性 即可。