There is a ApplicationUser. They can have multiple TfsAccounts and one TfsToken. A TfsAccount can have multiple TrackedTasks.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<TfsAccount> TfsAccounts { get; set; }
public virtual TfsToken TfsToken { get; set; }
}
public class TfsAccount
{
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public string ApplicationUserId { get; set; }
public virtual ICollection<TrackedTask> TrackedTasks { get; set; }
}
public class TrackedTask
{
[ForeignKey("TfsAccountId")]
public virtual TfsAccount TfsAccount { get; set; }
public int TfsAccountId { get; set; }
}
Now, I have a method to cancel a subscription for a user and delete them:
[HttpGet]
public async Task<ActionResult> CancelSubscription()
{
var currentUser = UserManager.FindById(User.Identity.GetUserId());
var tfsAccounts = currentUser.TfsAccounts; <---REMOVE THESE
var tfsToken = currentUser.TfsToken; <---TWO LINES AND IT BREAKS
var result = await UserManager.DeleteAsync(currentUser); <---ON THIS LINE
AuthenticationManager.SignOut();
return RedirectToAction("CancellationConfirmed");
}
Here is the error I get in the browser:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.TfsAccounts_dbo.AspNetUsers_ApplicationUserId". The conflict occurred in database "TfsTeamStatus", table "dbo.TfsAccounts", column 'ApplicationUserId'.
The statement has been terminated.
Why do I have to access the related fields on the user before I can delete the user? This works but feels super hacky.