简体   繁体   English

内存数据库的 Dbset 返回具有空集合导航属性的实体

[英]Dbset of in memory database returns entity with empty collection navigation property

The problem with the test:测试的问题:

[Fact]
public async Task CountOfDaysOffInCurrentYearToToday()
{
    var application1 = new Domain.Entities.Application
    {
        Type = ApplicationType.DayOff, Status = ApplicationStatus.Approved, StatedDates =
        {
            new ApplicationDate { Date = new DateTime(2021, 4, 1) },
            new ApplicationDate { Date = new DateTime(2022, 4, 1) },
            new ApplicationDate { Date = new DateTime(2023, 4, 1) }
        }
    };

    var application2 = new Domain.Entities.Application
    {
        Type = ApplicationType.DayOffAtExpenseOfVacation, Status = ApplicationStatus.Approved, StatedDates =
        {
            new ApplicationDate { Date = new DateTime(2021, 4, 1) },
            new ApplicationDate { Date = new DateTime(2022, 4, 1) },
            new ApplicationDate { Date = new DateTime(2023, 4, 1) }
        }
    };

    var application3 = new Domain.Entities.Application
    {
        Type = ApplicationType.DayOffAtExpenseOfVacation, Status = ApplicationStatus.Approved, StatedDates =
        {
            new ApplicationDate { Date = new DateTime(2021, 4, 1) },
            new ApplicationDate { Date = new DateTime(2022, 4, 1) },
            new ApplicationDate { Date = new DateTime(2023, 4, 1) }
        }
    };

    var user = new AppUser
    {
        ApplicantApplications = { application1, application2, application3 }
    };

    var context = GetDbContext();
    await context.Users.AddAsync(user);
    await context.SaveChangesAsync();

    var bl = new UserCalendarBL(context, GetDateTime());

    Assert.Equal(4, await bl.CountOfDaysOffInCurrentYearToToday(user.Id));
}

When I debug it, it shows that StatedDates is empty in every application:当我调试它时,它显示每个应用程序中的StatedDates都是空的:

在此处输入图像描述

private static IDbContext GetDbContext()
{
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseInMemoryDatabase(new StackFrame(1, true).GetMethod()!.Name)
        .Options;
    return new AppDbContext(options);
}
private IDateTimeService GetDateTime()
{
    var mock = new Mock<IDateTimeService>();
    mock.Setup(e => e.Now()).Returns(new DateTime(2022, 5, 1));
    return mock.Object;
}

These are entity types:这些是实体类型:

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

    public AppUser Applicant { get; set; }
    public string ApplicantId { get; set; }

    public DateTime DateOfCreation { get; set; }
    public DateTime? DateOfSent { get; set; }

    public ApplicationType Type { get; set; }
    public ApplicationStatus Status { get; set; }

    public List<ApplicationDate> StatedDates { get; set; } = new List<ApplicationDate>();

    public AppUser Coordinator { get; set; }
    public string CoordinatorId { get; set; }

    public string Comment { get; set; }
}
public class AppUser : IdentityUser
{
    public List<Application> ApplicantApplications { get; set; } = new List<Application>();
    public List<Application> CoordinatorApplications { get; set; } = new List<Application>();
    public string FullName { get; set; }
    public string Position { get; set; }
    public int? CountOfUnusedVacationDaysOverPastYears { get; set; }
}
public class ApplicationDate
{
    public DateTime Date { get; set; }
    public int ApplicationId { get; set; }
    public Application Application { get; set; }
}

ApplicationDate has composite key of Date and ApplicationId ApplicationDate具有DateApplicationId的复合键

These are testing methods:这些是测试方法:

public async Task<int> CountOfDaysOffInCurrentYearToToday(string userId)
{
    return await Task.Run(() =>
    {
        var applications = ApprovedApplicationsInCurrentYearToToday(userId).AsParallel().Where(
            application =>
                application.Type == ApplicationType.DayOff ||
                application.Type == ApplicationType.DayOffAtExpenseOfVacation ||
                application.Type == ApplicationType.DayOffAtExpenseOfWorkingOut).ToImmutableArray();

        return applications.Sum(CountOfApplicationDatesInCurrentYearToToday);
    });
}
private IEnumerable<Domain.Entities.Application> ApprovedApplicationsInCurrentYearToToday(string userId)
{
    return _context.Applications
        .Include(application => application.Applicant)
        .AsNoTracking()
        .AsParallel()
        .Where(application =>
            application.Applicant.Id == userId &&
            GetApplicationStatedDates(application)
                .Any(date => date.Year == _dateTime.Now().Year && date < _dateTime.Now()));
}

In the where method, by stopping on a breakpoint, I can verify that StatedDates is empty.在 where 方法中,通过在断点处停止,我可以验证StatedDates是否为空。

You have to load the navigation property StatedDates explicitly like this:您必须像这样显式加载导航属性StatedDates

private IEnumerable<Domain.Entities.Application> ApprovedApplicationsInCurrentYearToToday(string userId)
{
    return _context.Applications
        .Include(application => application.Applicant)
        .Include(application => application.StatedDates)
        .AsNoTracking()
        .AsParallel()
        .Where(application =>
            application.Applicant.Id == userId &&
            GetApplicationStatedDates(application)
                .Any(date => date.Year == _dateTime.Now().Year && date < _dateTime.Now()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果没有 DbSet 属性,是否在数据库内存中创建表? - Is the table created in database memory if there is no DbSet property? 重新加载一个实体和所有导航属性关联- DbSet 实体框架 - Reload an entity and all Navigation Property Association- DbSet Entity Framework EF:将导航属性包含在DbSet中添加实体的结果中 - EF: Include navigation property to result of adding entity in DbSet Entity Framework Core:基于导航属性的集合 - Entity Framework Core: navigation property based collection 没有集合导航属性的实体框架一对多 - Entity Framework One to Many with no Collection navigation property EF Core-从集合导航属性中删除相关实体不会更新数据库 - EF Core - Removing a related entity from collection navigation property does not update database 筛选器导航属性实体框架,返回NULL - Filter Navigation Property Entity Framework, returns NULL 数据库设计实体框架中的导航属性 - Navigation property in Entity Framework for a Database Design 使用已存在的导航属性将实体添加到数据库 - Adding an entity to database with a navigation property that already exists 实体框架5:为什么我的实体的集合属性为空? - Entity Framwork 5: Why is my entity's collection property empty?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM