实体框架,当包含一对多关系项时,获取数据不断加载而没有结果

问题描述 投票:0回答:1

我有一个与证书具有一对多关系的员工实体(1名员工可以拥有多个证书),下面是我的实体类

    public sealed class UserProfileAggregate : AggregateRoot<UserProfileId>
    {
    private readonly List<Certificate> _certificates = [];

    [JsonIgnore]
    public JobTitleId JobTitleId { get; private set; }
    public JobTitle JobTitle { get; private set; }

    [JsonIgnore]
    public DepartmentId DepartmentId { get; private set; }
    public Department Department { get; private set; }

    [JsonIgnore]
    public SectionId SectionId { get; private set; }
    public Section Section { get; private set; }

    public DateTime JoinDate { get; private set; }

    public IReadOnlyList<Certificate> Certifications => _certificates.ToList();

    ...
    }

    public class Certificate : Entity<CertificateId>
    {
    public string Title { get; }

    public string IssuedBy { get; }

    public Country Country { get; }

    public DateTime CertificateDate { get; }

    public UserProfileAggregate UserProfileAggregate { get; }
    }

关系的定义如下

    builder.HasMany(up => up.Certificates)
   .WithOne()
   .HasForeignKey("UserProfileAggregateId")
   .IsRequired();

当我使用实体框架核心来获取用户个人资料时,我没有得到任何结果,并且 API 会永远加载。

    public async Task<List<UserProfileAggregate>> GetUserProfiles()
    {
        var result = await _dbContext.UserProfiles
            .AsNoTracking()
            .Include(up => up.JobTitle)
            .Include(up => up.Department)
            .Include(up => up.Section)
            .Include(up => up.Certifications)
            .ToListAsync();

        return result;
    }

一切正常,我删除了“Include(up => up.Certifications)”

我尝试单独获取认证数据,然后将其与用户配置文件对象绑定,它有效,但这不是我想要的。我希望能够获得包含所有信息的完整对象。

下面是生成的查询

SELECT [u].[Id], [u].[DepartmentId], [u].[JobTitleId], [u].[JoinDate], [u].[SectionId], [j].[Id], [j].[Level], [j].[Title], [d].[Id], [d].[Name], [s].[Id], [s].[Name], [a].[Id], [a].[Title], [a].[IssuedBy], [a].[UserProfileAggregateId]
FROM [UserProfileAggregates] AS [u]
INNER JOIN [JobTitles] AS [j] ON [u].[JobTitleId] = [j].[Id]
INNER JOIN [Departments] AS [d] ON [u].[DepartmentId] = [d].[Id]
INNER JOIN [Sections] AS [s] ON [u].[SectionId] = [s].[Id]
LEFT JOIN [Certificates] AS [a] ON [u].[Id] = [a].[UserProfileAggregateId]
ORDER BY [u].[Id], [j].[Id], [d].[Id], [s].[Id]
c# .net entity-framework domain-driven-design
1个回答
0
投票

不建议在实体类本身中使用 ToList()。另请检查循环引用和延迟加载,其中相关实体在访问时立即加载。

© www.soinside.com 2019 - 2024. All rights reserved.