2017-08-11 76 views
0

我使用默認模型類和SQLite作爲數據庫的asp.net mvc核心web應用程序。 我對下面的代碼刪除用戶:在asp.net mvc核心中刪除用戶的奇怪例外

var user = await _dbContext.Users.SingleOrDefaultAsync(s => s.Id == id); 
try 
{ 
    await _userManager.DeleteAsync(user); 
} 
catch (Exception) 
{ 
} 

刪除大多數用戶都不錯,但對於某些用戶我得到了不同的異常,如:System.ObjectDisposedExceptionSystem.InvalidOperationException: 'BeginTransaction can only be called when the connection is open.'在這種情況下,用戶不會被刪除。爲什麼相同的代碼對於不同的用戶來說可能很奇怪?

回答

0

問題是,我有類也存儲在DB:

public class Coordinate 
{ 
    public int ID { get; set; } 
    public double Lat { get; set; } 
    public double Lon { get; set; } 

    [JsonIgnore] 
    public ApplicationUser User { get; set; } 
} 

所以,如果我想刪除用戶,其中有座標 - 我得到一個錯誤。我必須先刪除用戶的座標:

  var coordinates = _dbContext.Coordinates.Where(x => x.User == user).ToList(); 
      _dbContext.Coordinates.RemoveRange(coordinates);