繁体   English   中英

无法成功从数据库中删除记录

[英]Cannot successfully delete record from the database

难道我做错了什么? 一切似乎都还可以,但是记录不会从数据库中删除:

C#

    @{
    WebSecurity.RequireAuthenticatedUser();

    myModel.OSFEntities database = new myModel.OSFEntities();

    var productInformation = Request["Pi"];

    int productId = Convert.ToInt32(productInformation.Substring(0, productInformation.LastIndexOf("-")));
    string productType = productInformation.Substring(productInformation.LastIndexOf("-", productInformation.Length)).Replace("-", String.Empty);
    var userId = WebSecurity.CurrentUserId;
    DateTime date = DateTime.Now;
    int quantity = 1;
    string quoteId = "";

    if (Request["Action"] == "Remove")
    {
        if (Session["QuoteId"] != null)
        {
            quoteId = (String)Session["QuoteId"];

            myModel.Quote quotes = database.Quotes.FirstOrDefault(
                q => q.UserId == userId && q.QuoteId == quoteId && q.ProductId == productId && q.ProductType == productType);

            database.Quotes.DeleteObject(quotes);
            database.SaveChanges();
        }
    }
}

打字稿:

function RemoveProductFromCart(e) {
    // Remove from their Cart.
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                // The data is now stored in the responseText.
                // Change value in textbox to 0 so user knows it's been
                // removed from their cart.
                var el = <HTMLInputElement>document.getElementById(e.id + "-TB");
                if (el != null) {
                    el.value = "0";
                }
            }

            else {
                // Server responded with a different response code.
                alert(xhr.statusText);
            }

        }
    }

    var parameters = "Pi=" + encodeURIComponent(e.id) + "&" + "Action=Remove";

    xhr.open("POST", "../Cart.cshtml");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", parameters.length.toString());
    xhr.setRequestHeader("Connection", "close");
    xhr.send(parameters);

    return e.id;
}

使用F12开发工具进行调试时,我看到:

在此处输入图片说明

...这使我相信我的C#代码有问题。 为什么不从数据库中删除?

我有一些建议。

在这些情况下,总是很可能其中一个请求项与您认为的不完全一样,因此操作或报价ID可能都包含一个惊喜。 您可以使用断点检查那些对象。

下一个要检查的项目是myModel.Quote quotes包含匹配的引号对象。 即使ID正确(例如,它未链接到当前用户,或者产品类型不同,等等),您可能拥有的一个过滤器仍将其排除在外。

我注意到您正在使用...

database.Quotes.DeleteObject(quotes);
database.SaveChanges();

也就是说,您在第一个而不是第二个上使用Quotes :是否不应将SaveChangesDeleteObject调用放在同一上下文中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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