I'm working on a Blazor Server App and I use the following code to add data to the database (using service repository):
async Task<string> ISoftwareSectionUserService.SetSoftwareSectionPermissions(Dictionary<string, string> softwareSections, int userId)
{
try
{
var newUserSoftwareSections = new List<UserSoftwareSection>();
var selectedItemsToDelete = await _sqliteContext.UserSoftwareSections.Where(x => x.UserRef == userId).ToListAsync();
await _sqliteContext.BulkDeleteAsync(selectedItemsToDelete);
await _sqliteContext.SaveChangesAsync();
foreach (var item in softwareSections)
{
var selectedSectionUser = await _sqliteContext.UserSoftwareSections
.FirstOrDefaultAsync(x => x.UserRef == userId && x.SoftwareSectionRefNavigation.SectionName == item.Key);//Key is section name
var selectedSection = await _sqliteContext.SoftwareSections.FirstOrDefaultAsync(x => x.SectionName == item.Key);//Value is permision string
if (selectedSectionUser == null)
{
var userSoftwareSection = new UserSoftwareSection
{
UserRef = userId,
SectionRef = (int)selectedSection?.SectionId,
Permissions = item.Value
};
newUserSoftwareSections.Add(userSoftwareSection);
}
}
await _sqliteContext.BulkInsertAsync(newUserSoftwareSections, config => config.BatchSize = 100);
await _sqliteContext.SaveChangesAsync();
return JsonConvert.SerializeObject(new ServiceResultModel<string> { Succeed = true });
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new ServiceResultModel<string> { Succeed = false, Message = (ex.Message + "\\ " + ex.InnerException) });
}
}
And, I use the following codes to load data from database:
async Task<string> ISoftwareSectionUserService.GetUserSoftwareSections(int userId)
{
try
{
var softwareSectionsList = await _sqliteContext.UserSoftwareSections.Include(x => x.SoftwareSectionRefNavigation).Where(x => x.UserRef == userId).ToListAsync();
var settings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
return JsonConvert.SerializeObject(new ServiceResultModel<List<UserSoftwareSection>> { Succeed = true, Data = softwareSectionsList }, settings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new ServiceResultModel<string> { Succeed = false, Message = (ex.Message + "\\ " + ex.InnerException) });
}
}
When I loaded the data for the first time, it is based on database enries. But, when I add data to the database using SetSoftwareSectionPermissions
and try to load them using GetUserSoftwareSections
, the last data is shown, not the actual data in database (It shows database data only after page reload).
I studied some posts such as this one and tried to reload SqliteContext
. But when I reload database using await _sqliteContext.Entry(softwareSectionsList).ReloadAsync();
, there is an error saying:
The entity type 'List' was not found. Ensure that the entity type has been added to the model.
How can I solve this problem?