Home > other >  DbContext doesn't load data properly from database
DbContext doesn't load data properly from database

Time:12-21

I have a .NET application where users can create/edit their filters and a second console application which runs as background task and applies their filters.

I extended Application use class:

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        Filters = new List<FilterData>();
    }

    [SqlDefaultValue(DefaultValue = 0)]
    public long Credit { get; set; }

    public virtual ICollection<FilterData> Filters { get; set; }
}

My console application creates a DbContext and tries to use Filters property:

static void Main(string[] args)
{
    var contextOptions = new DbContextOptionsBuilder<ApplicationDbContextEx>()
            .UseSqlServer(@"connection string....")
            .Options;

    ApplicationDbContextEx context = new ApplicationDbContextEx(contextOptions);

    foreach (var user in context.Users.ToList())
    { 
        // Filters 
        Debug.Assert(user.Filters != null, "weird because we have filters in db");      
    }
}

My problem is that user.Filters is always null even when there are valid filters in the database.

I would guess it is issue with DbContext creation.

Thanks for help !

CodePudding user response:

Have you defined the relationship using either convention, attributes or the FluentAPI? Try using Include:

foreach (var user in context.Users.Include(a => a.Filters).ToList())
{
}
  • Related