【发布时间】:2017-08-29 18:44:46
【问题描述】:
我正在尝试删除重复但聪明的用户,他们发现他们可以使用多个电子邮件创建帐户。我的应用程序有一个 UserLog 让我可以通过站点跟踪我的用户以进行风险管理。这是我的 UserLog 类:
public class UserLog
{
public int Id { get; set; }
public ApplicationUser Customer { get; set; }
public DateTime LogDate { get; set; }
}
在我的ManageUsers 控制器中,我知道我需要在删除用户之前删除用户创建的日志,因为我在课堂上创建了FK_constraint。最后我尝试删除用户。这是我尝试过的:
public ActionResult Delete(string UserName)
{
var ocustomerId = User.Identity.GetUserId();
var oCustomer = _context.Users.Single(u => u.Id == ocustomerId).ToString();
//delete user logs
_context.UserLogs
.Where(p => p.Customer.Id == oCustomer)
.ToList()
.ForEach(p => _context.UserLogs.Remove(p));
_context.SaveChanges();
//finally delete from aspnetUsers table
var thisUser =
_context.Users.FirstOrDefault(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));
_context.Users.Remove(thisUser);
_context.SaveChanges(); \\it breaks here
return RedirectToAction("Index");
}
正如预期的那样,代码的第一部分按预期工作,删除了用户创建的日志。错误发生在第二个context.SaveChanges()。
断点产生的错误是:
EntityFramework.dll 中出现 DbUpdateException 错误
而实际错误页面产生的错误如下:
DELETE 语句与 REFERENCE 约束“FK_dbo.UserLogs_dbo.AspNetUsers_Customer_Id”冲突。发生了冲突 在数据库“myDB”、表“dbo.UserLogs”、“Customer_Id”列中。这 语句已终止。
【问题讨论】:
标签: c# asp.net-mvc entity-framework asp.net-identity