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

时间:2012-10-30 13:23:15

标签: c# javascript asp.net entity-framework typescript

我做错了吗?一切似乎都没问题,但记录不会从数据库中删除:

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 Dev Tools进行调试时,我看到:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

我有一些建议。

在这些情况下,其中一个请求项很可能不是您认为的那样,因此操作或引用ID可能包含一个惊喜。你可以使用断点检查那些。

要检查的下一个项目是myModel.Quote quotes包含匹配的引用对象。也许你所拥有的过滤器之一就是排除它,即使id是正确的(例如它没有链接到当前用户,或者产品类型不同等)。

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

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

即。您在第一个而不是第二个上使用QuotesSaveChangesDeleteObject调用是否应该针对相同的上下文?

相关问题