Home > Enterprise >  The entity type 'EntityQueryable<Entrys>' was not found. Ensure that the entity type
The entity type 'EntityQueryable<Entrys>' was not found. Ensure that the entity type

Time:09-22

I have a scenario, I have users submitting entries to an epi end point and a flag is updated as 1 on the database. A user can submit more than entry as per there feel and need per time. I have a logic that checks if an entry all ready exists, and if a user submits another form, the previous form is set to 0 and the new form is set to 1. Whenever I submit a second entry I end up with an error

The entity type 'EntityQueryable' was not found. Ensure that the entity type has been added to the model. at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(Object entity)

this is my logic for checking

public async Task<Entrys> AddEntrys(Entrys entrys)
        {

            var pastSurveys = _context.Entrys.Where(e => e.UpdatedBy == entrys.UpdatedBy && e.Month == entrys.Month
           && e.Day == entrys.Day && e.Year == entrys.Year && e.CurrentStatus==true).AsQueryable();

            if (pastSurveys.Count() > 0)
            {
                foreach (Entrys e in pastSurveys)
                {
                    if (e.CurrentStatus == true)
                    {
                        e.CurrentStatus = false;
                    }
                }
                _context.Add(pastSurveys);
                _context.SaveChanges();
            }
            entrys.Id = Guid.NewGuid().ToString();
            _context.Add(entrys);
            _context.SaveChanges();
            return entrys;
        }

How can I have my logic to keep on checking the existing surveys and updating them to 0 while new ones are set to 1 without getting the error above, Have tried researching no luck do far. Thank you in advance

CodePudding user response:

Problem that instead of Updating entities you inserts them. Also you do not need two SaveChanges calls. pastSurveys.Count() also executes unwanted query.

Corrected method:

public async Task<Entrys> AddEntrys(Entrys entrys)
{
    var pastSurveys = _context.Entrys
        .Where(e => e.UpdatedBy == entrys.UpdatedBy && e.Month == entrys.Month
            && e.Day == entrys.Day && e.Year == entrys.Year && e.CurrentStatus == true)
        .ToList();

    foreach (Entrys e in pastSurveys)
    {
        e.CurrentStatus = false;
    }
    
    entrys.Id = Guid.NewGuid().ToString();
    _context.Add(entrys);
    _context.SaveChanges();
    return entrys;
}

CodePudding user response:

Hi @arrif from your implementation

change the _context.Add(pastSurveys); to _context.UpdateRange(pastSurveys);

From your current setup you adding instead of updating the flag. Try that and tell if it works cheers

  • Related