删除和保存EF中的更改时出现DbUpdateException

时间:2017-04-02 00:32:45

标签: asp.net-mvc entity-framework

我试图通过简单地使用db.'table'.remove('object')删除数据库中的记录,但是当调用MatrixXd resultEigen; // Eigen matrix with some result (non NULL!) double *resultC; // NULL pointer Map<MatrixXd>( resultC, resultEigen.rows(), resultEigen.cols() ) = resultEigen; 异常时抛出异常。

  

'EntityFramework.dll中出现'System.Data.Entity.Infrastructure.DbUpdateException'类型的异常,但未在用户代码中处理

我在控制器中的删除方法

db.SaveChanges()

型号:

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    db.Customers.Remove(customer);
    db.SaveChanges();

    return RedirectToAction("Index");
}

部分例外:

public class Customer
{
    [Key, ForeignKey("User")]
    public int UserId { get; set; }
    public string Email { get; set; }
    public virtual CreditCard CreditCard { get; set; }
    public virtual ShoppingCart ShoppingCart { get; set; }
    public virtual List<Enquiry> Enquiries { get; set; }
    public virtual List<Order> Orders { get; set; }
    public virtual User User { get; set; }
}
public class User
{
    [Key]
    public int Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public string FirstName { set; get; }
    public string Surname { set; get; }
    public virtual UserRole UserRole { get; set; }
}

public class ShoppingCart
    {
        [Key, ForeignKey("Customer")]
        public int Id { get; set; }
        public virtual List<CartItem> CartItems { get; set; }
        public virtual Customer Customer { get; set; }
    }

完全例外:

A DbUpdateException was caught while saving changes. Type: Customer_8D9A6B7F7D247C9CB9F95E830039791E299E94FC91841FD33610DD1804AEF739 was part of the problem. 

1 个答案:

答案 0 :(得分:0)

您似乎还有另一个名为dbo.ShoppingCarts的表格,其中有一个购物车,其中有一行或多行与您要删除的客户相关。 首先,您必须删除与该客户相关的行,然后才能删除该客户。发生这种情况是因为客户ID是该另一个表中的外键 如果情况并非如此,请将您的ShoppingCarts类添加到问题中。