使用 .Include() 检索数据时,Entity Framework Core 中出现意外的循环引用

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

我正在 Entity Framework Core 中开发一个存储库方法来检索所有应用程序及其关联的应用程序令牌。我的方法如下:

public async Task<IEnumerable<ApplicationDTO>> GetAllApplications(string? expand = null)
{
    List<Application> applications = await context.Applications.Include(a => a.ApplicationTokens).ToListAsync();

    return mapper.Map<IEnumerable<ApplicationDTO>>(applications);
}

我希望结果是一个 Application 对象列表,每个对象都包含一个 ApplicationToken 对象列表。重要的是,我不希望 ApplicationToken 对象包含对 Application 对象的反向引用,因为我没有在查询中指定

.ThenInclude(t => t.Application)
。以下是实体定义:

public class Application
{
    public int Id { get; set; }

    public required string Name { get; set; }

    public required string Description { get; set; }

    public DateTime CreatedAt { get; set; }

    public required int CreatedById { get; set; }

    public User? CreatedBy { get; set; }

    public ICollection<ApplicationToken>? ApplicationTokens { get; set; }

    public ICollection<FeatureGate>? FeatureGates { get; set; }
}

public class ApplicationToken
{
    public int Id { get; set; }

    public required int ApplicationId { get; set; }

    public required string Token { get; set; }

    public required bool Enabled { get; set; }

    public required DateTime CreatedAt { get; set; }

    public required int CreatedById { get; set; }

    public required DateTime ExpiresAt { get; set; }

    public Application? Application { get; set; }

    public User? CreatedBy { get; set; }
}

在映射到 ApplicationDTO 之前,我观察到了 Application 和 ApplicationToken 实体之间的循环引用,我的目的是避免这种情况。我的期望是应用程序令牌将填充在每个应用程序中,而无需反向引用应用程序本身,从而防止任何循环引用。我没有可以自动填充这些引用的延迟加载或虚拟集合。

我在这里缺少什么?

c# entity-framework-core circular-reference
1个回答
0
投票

如果您使用 Automapper,请使用

ProjectTo<TDto>()
。其他映射库具有类似的方法来使用 EF 的
IQueryable
,而不是获取实体和关系,然后调用
Map<TDto>()
。这将避免潜在的循环引用。

只需确保您没有尝试混合 DTO 和实体,例如创建包含 ApplicationToken 实体的 ApplicationDTO,因为这些实体将引用应用程序实体、引用令牌等。如果您尝试序列化 ApplicationDTO将序列化所包含的实体,从而导致循环引用问题。如果您希望在 ApplicationDTO 中使用令牌,请创建 ApplicationTokenDTO 并配置映射器以将这些实体也转换为 DTO。

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