簡體   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