Database operation expected to affect 1 row(s) but actually affected 0 row(s).解決方案

SELECT changes();
引發的異常:“Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException”(位於 Microsoft.EntityFrameworkCore.dll 中)
“Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException”類型的異常在 Microsoft.EntityFrameworkCore.dll 中發生,但未在用戶代碼中進行處理
Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

 

報了這個錯,官方說是併發引起,就我自己,哪來併發?網上的其他答案也沒解決我的問題。

最後我偶然解決了這個問題,作爲引發此異常的原因之一,記錄一下,幫助有需要的人。

我的數據庫實體類定義了構造函數,然後沒有聲明默認構造函數,導致EF創建實體失敗,導致了此異常。

 

解決方案:

在你自定義構造函數後面補充個默認構造函數

 

    public class KeyValue
    {
        [Key]
        public string Key { get; set; }
        public string Value { get; set; }
        public string Type { get; set; }

        public KeyValue(string key, string value, string type)
        {
            Key = type + ":" + key;
            Value = value;
            Type = type;
        }

        public KeyValue()
        { }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章