How to delete records from database correctly

Viewed 44

While I was trying to delete records from databse in wep api, occurred with error "System.InvalidOperationException: There is already an open DataReader associated with this Connection which must be closed first". Method body:

 [HttpDelete]
[Route("/DeleteUrls")]
public async Task<IActionResult> DeleteUrls(string userName)
{
    var user = _dataContext.Users.FirstOrDefault(x => x.UserName == userName);
    if (user==null)
    {
        return BadRequest("No user with such Username");
    }
    switch (user.IsAdmin)
    {
        case true:
            var longUrls2Remove =  _dataContext.Urls.AsQueryable();
            foreach (var item in longUrls2Remove)
            {
                var shortUrl2Remove = _dataContext.ShortedUrls.FirstOrDefault(x => x.Url == item);
                _dataContext.ShortedUrls.Remove(shortUrl2Remove);
                _dataContext.Urls.Remove(item);
            }
            await _dataContext.SaveChangesAsync();
            return Ok();
        
        case false:
            var longUrlsToRemove = _dataContext.Urls.Where(x => x.UserCreatedBy == user);
            foreach (var item in longUrlsToRemove)
            {
                var shortUrlToRemove = _dataContext.ShortedUrls.FirstOrDefault(x => x.Url == item);
                _dataContext.ShortedUrls.Remove(shortUrlToRemove);
                _dataContext.Urls.Remove(item);
                
                await _dataContext.SaveChangesAsync();
                return Ok();
            }

            return BadRequest();
    }
}

Logic is to delete all records if user is admin, and only his own if he isnt. Database structure:

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public bool IsAdmin { get; set; }

    public List<Url> Urls { get; set; }
}

public class Url
{
    public int Id { get; set; }
    public string OriginalUrl { get; set; }
    public DateTime CreatedAt { get; set; }

    public int UserId { get; set; }
    public User UserCreatedBy { get; set; }
    
    public ShortUrl ShortUrl { get; set; }
    
}
public class ShortUrl
{
    public int Id { get; set; }
    public string ShortedUrl { get; set; }

    public int UrlId { get; set; }
    public Url Url { get; set; }
}

Obviously the problem is with another open connetion, but I dont get any idea how to implement this method correctly.

1 Answers

Reason : you are executing two or more queries at the same time.

Solution : add ToList() after query.

var longUrlsToRemove = _dataContext.Urls.Where(x => x.UserCreatedBy == user).ToList()

IQueryable is not a collection of entities in memory. ToList() stores records in memory. So you don't connect to database in every loop.

Related