EF核心导航属性未加载

时间:2019-04-11 14:23:57

标签: c# entity-framework-core navigation-properties

我正在修改我的应用程序,以便能够指定要在存储库中加载的导航属性。

模型:可以在domain entites中找到Team和TeamTunerUser。

存储库:

namespace Sppd.TeamTuner.Infrastructure.DataAccess.EF.Repositories
{
    internal class Repository<TEntity> : IRepository<TEntity>
        where TEntity : BaseEntity
    {
        /// <summary>
        ///     Gets the entity set.
        /// </summary>
        protected DbSet<TEntity> Set => Context.Set<TEntity>();

        /// <summary>
        ///     Gets the DB context.
        /// </summary>
        protected TeamTunerContext Context { get; }

        public Repository(TeamTunerContext context)
        {
            Context = context;
        }

        public async Task<TEntity> GetAsync(Guid entityId, IEnumerable<string> includeProperties = null)
        {
            TEntity entity;
            try
            {
                entity = await GetQueryableWithIncludes(includeProperties).SingleAsync(e => e.Id == entityId);
            }
            catch (InvalidOperationException)
            {
                throw new EntityNotFoundException(typeof(TEntity), entityId.ToString());
            }

            return entity;
        }

        protected IQueryable<TEntity> GetQueryableWithIncludes(IEnumerable<string> includeProperties = null)
        {
            var queryable = Set;

            if (includeProperties == null)
            {
                return queryable;
            }

            foreach (var propertyName in includeProperties)
            {
                queryable.Include(propertyName);
            }

            return queryable;
        }
    }
}

测试:

    [Fact]
    public async Task TestNavigationPropertyLoading()
    {
        // Arrange
        var teamId = Guid.Parse(TestingConstants.Team.HOLY_COW);

        // Act
        Team createdTeamWithoutUsers;
        Team createdTeamWithUsers;
        using (var scope = ServiceProvider.CreateScope())
        {
            var teamRepository = scope.ServiceProvider.GetService<IRepository<Team>>();

            createdTeamWithoutUsers = await teamRepository.GetAsync(teamId);
            createdTeamWithUsers = await teamRepository.GetAsync(teamId, new[] {nameof(Team.Users)});
        }

        // Assert
        Assert.Null(createdTeamWithoutUsers.Leader);
        Assert.False(createdTeamWithoutUsers.Users.Any());
        Assert.False(createdTeamWithUsers.CoLeaders.Any());

        Assert.NotNull(createdTeamWithUsers.Leader);
        Assert.True(createdTeamWithUsers.Users.Any());
        Assert.True(createdTeamWithUsers.CoLeaders.Any());
    }

我的问题是Users导航属性从不加载,第二个断言块失败。

在此处(class)配置了团队:

    private static void ConfigureTeam(EntityTypeBuilder<Team> builder)
    {
        ConfigureDescriptiveEntity(builder);

        builder.HasMany(e => e.Users)
               .WithOne(e => e.Team);

        // Ignore calculated properties
        builder.Ignore(e => e.Members)
               .Ignore(e => e.Leader)
               .Ignore(e => e.CoLeaders);
    }

(调试)日志不包含任何有用的内容,只是我发现加载导航属性所需的联接未在SQL级别上执行:

2019-04-11 16:02:43,896 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Opening connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:43,901 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Opened connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:43,903 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Command - Executing DbCommand [Parameters=[@__entityId_0='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [m].[Id], [m].[Avatar], [m].[CreatedById], [m].[CreatedOnUtc], [m].[DeletedById], [m].[DeletedOnUtc], [m].[Description], [m].[FederationId], [m].[IsDeleted], [m].[ModifiedById], [m].[ModifiedOnUtc], [m].[Name]
FROM [Team] AS [m]
WHERE ([m].[IsDeleted] = 0) AND ([m].[Id] = @__entityId_0)
2019-04-11 16:02:43,920 [12] INFO  Microsoft.EntityFrameworkCore.Database.Command - Executed DbCommand (16ms) [Parameters=[@__entityId_0='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [m].[Id], [m].[Avatar], [m].[CreatedById], [m].[CreatedOnUtc], [m].[DeletedById], [m].[DeletedOnUtc], [m].[Description], [m].[FederationId], [m].[IsDeleted], [m].[ModifiedById], [m].[ModifiedOnUtc], [m].[Name]
FROM [Team] AS [m]
WHERE ([m].[IsDeleted] = 0) AND ([m].[Id] = @__entityId_0)
2019-04-11 16:02:43,945 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Command - A data reader was disposed.
2019-04-11 16:02:43,985 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Closing connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:43,988 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Closed connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:45,054 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Opening connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:45,057 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Opened connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:45,060 [12] DEBUG Microsoft.EntityFrameworkCore.Database.Command - Executing DbCommand [Parameters=[@__entityId_0='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [m].[Id], [m].[Avatar], [m].[CreatedById], [m].[CreatedOnUtc], [m].[DeletedById], [m].[DeletedOnUtc], [m].[Description], [m].[FederationId], [m].[IsDeleted], [m].[ModifiedById], [m].[ModifiedOnUtc], [m].[Name]
FROM [Team] AS [m]
WHERE ([m].[IsDeleted] = 0) AND ([m].[Id] = @__entityId_0)
2019-04-11 16:02:45,067 [14] INFO  Microsoft.EntityFrameworkCore.Database.Command - Executed DbCommand (7ms) [Parameters=[@__entityId_0='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
SELECT TOP(2) [m].[Id], [m].[Avatar], [m].[CreatedById], [m].[CreatedOnUtc], [m].[DeletedById], [m].[DeletedOnUtc], [m].[Description], [m].[FederationId], [m].[IsDeleted], [m].[ModifiedById], [m].[ModifiedOnUtc], [m].[Name]
FROM [Team] AS [m]
WHERE ([m].[IsDeleted] = 0) AND ([m].[Id] = @__entityId_0)
2019-04-11 16:02:45,092 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Command - A data reader was disposed.
2019-04-11 16:02:45,143 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Closing connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.
2019-04-11 16:02:45,153 [14] DEBUG Microsoft.EntityFrameworkCore.Database.Connection - Closed connection to database 'Sppd.TeamTuner-TEST' on server '.\SQLEXPRESS'.

我尝试过的事情:

  • 不指定字符串,而是指定要加载的导航属性的表达式:

    protected IQueryable<TEntity> GetQueryableWithIncludes(IEnumerable<string> includeProperties = null)
    {
        var queryable = Set;
    
        if (includeProperties == null)
        {
            return queryable;
        }
    
        if (typeof(TEntity) == typeof(Team))
        {
            // TODO: Remove this block once it works by including by string properties
            foreach (var propertyName in includeProperties)
            {
                if (propertyName == "Users")
    
                {
                    queryable.OfType<Team>().Include(entity => entity.Users);
                }
            }
        }
        else
        {
            foreach (var propertyName in includeProperties)
            {
                queryable.Include(propertyName);
            }
        }
    
        return queryable;
    }
    
  • 也明确配置用户实体的关系:

    private static void ConfigureTeamTunerUser(EntityTypeBuilder<TeamTunerUser> builder)
    {
        ConfigureDescriptiveEntity(builder);
    
        builder.HasMany(e => e.CardLevels)
               .WithOne(e => e.User);
    
        builder.HasOne(e => e.Team)
               .WithMany(e => e.Users);
    
        // Indexes and unique constraint
        builder.HasIndex(e => e.Name)
               .IsUnique();
        builder.HasIndex(e => e.SppdName)
               .IsUnique();
        builder.HasIndex(e => e.Email)
               .IsUnique();
    }
    

我想念什么?

3 个答案:

答案 0 :(得分:3)

Include / ThenInclude(以及所有其他EF Core Queryable扩展名)就像常规LINQ Queryable方法(SelectWhereOrderBy等)修改源IQueryable<>,并返回修改后的IQueryable<>

在这里,您只是忘了使用结果查询,所以

queryable.Include(propertyName);

具有与

相同的效果
queryable.Where(e => false);

无效

只需将代码更改为

queryable = queryable.Include(propertyName);

答案 1 :(得分:1)

我注意到了一些问题。

您的方法仅适用于加载第一级导航属性。

foreach (var propertyName in includeProperties)
{
    queryable.Include(propertyName);
} 

您必须使用.ThenInclude()来加载嵌套的导航属性。但这破坏了您将IEnumerable<string> includeProperties = null作为构造函数的方法。

第二个问题与您的测试本身有关。它仅检查.Any(),但根据测试的名称,这是错误的断言。 (我们不知道测试是否失败,因为导航属性从未成功加载 OR ,但确实加载成功,但是Users为零。您应该检查的是导航属性是否为加载。类似于以下内容。

DbContext.Entry(createdTeamWithUsers).Navigation("Users").IsLoaded

答案 2 :(得分:0)

您是否尝试过将您的媒体资源标记为虚拟?您需要它来根据文档启用延迟加载导航:

  

延迟加载

     

然后,EF Core将为所有可以覆盖的导航属性启用延迟加载,也就是说,它必须是虚拟的并且在可以继承的类上。例如,在以下实体中,Post.Blog和Blog.Posts导航属性将被延迟加载。

     

Source: Loading Related Data