简体   繁体   中英

How to delete records from database correctly

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM