EF Core .ThenInclude 不包含外部实体并导致查询不检索任何内容

EF Core .ThenInclude does not include foreign entity and causes query to retrieve nothing

我这里有一个 EF Core 项目,但我在多级包含方面确实遇到了困难。我正在尝试查询像这样相关的条目:

  1. 有一个从 accountid 到 accountid 的 "friend" 关系映射 table。所以第一层就是这个映射实体。

  2. 映射中帐户的 ID table 是与相应帐户实体相关的外键。

  3. 在帐户实体中,有一个帐户在线状态实体的外键。

所以 tl;博士; FriendsMappingTable -> Account -> AccountOnlineState.

这是我使用的代码:

public Task<List<TEntity>> Read(Expression<Func<TEntity, bool>> predicate, params Func<IQueryable<TEntity>, IQueryable<TEntity>>[] foreignIncludes) 
{
    return RunInContextWithResult(async dbSet =>
    {
        var query = dbSet.Where(predicate);

        query = foreignIncludes.Aggregate(query, (current, include) => include(current));

        return await query.ToListAsync();
    });
 }

private async Task<List<TEntity>> RunInContextWithResult([NotNull] Func<DbSet<TEntity>, Task<List<TEntity>>> dbFunc)
{
    await using var ctx = GetContext();

    return await dbFunc(ctx.Set<TEntity>());
}

这是我的呼吁:

var friends = await m_friendsMappingRepository.Read(
            x => x.Id == sessionContext.Account.Id,
            x => x.Include(y => y.Friend).ThenInclude(y => y.AccountOnlineStateEntity));

但是,使用此设置,查询将 return 什么也没有。如果我删除 .ThenInclude(),它至少会 return 给定帐户的相应朋友实体,OnlineState 实体设置为空。

以下是(精简的)实体:

public interface IEntity<TKeyType>
{
    [NotNull]
    [Key]
    [Column("Id")]
    public TKeyType Id { get; set; }
}

[Table("FriendsMapping")]
public class FriendsMappingEntity : IEntity<int>
{
    [ForeignKey("Account")]
    public int Id { get; set; }

    public AccountEntity Account { 
        get; 
        [UsedImplicitly] private set;
    }

    [Column("FriendId")]
    [ForeignKey("Friend")]
    public int FriendId { get; set; }

    public AccountEntity Friend
    {
        get; 
        [UsedImplicitly] private set;
    }
}

public class AccountEntity : IEntity<int>
{
    [ForeignKey("AccountOnlineStateEntity")]
    public int Id { get; set; }

    [CanBeNull]
    public AccountOnlineStateEntity AccountOnlineStateEntity { get; set; }

    [NotNull]
    public List<FriendsMappingEntity> FriendsTo { get; set; }

    [NotNull]
    public List<FriendsMappingEntity> FriendsFrom { get; set; }
}

public class AccountOnlineStateEntity : IEntity<int>
{
    public int Id { get; set; }

    [Column("OnlineState")]
    public AccountOnlineState OnlineState { get; set; }
}

更新

根据 Ivan 的建议,添加一个 InverseProperty 并从 Account.Id 中删除 ForeignKey。

    //[ForeignKey("AccountOnlineStateEntity")]
    public int Id { get; set; }

    [CanBeNull]
    [InverseProperty("Account")
    public AccountOnlineStateEntity AccountOnlineStateEntity { get; set; }

并向 AccountOnlineStateEntity 添加一个 属性

    [ForeignKey("Id")]
    public AccountEntity Account { get; set; }