Asp.net-Mvc

元數據集合中不存在身份為“ ”的成員。rn參數名稱: 身份

  • January 31, 2020

我在嘗試調試時簡化了程式碼:

[HttpPost]
   public ActionResult Register(User model)
   {
       DateTime bla = new DateTime(2012, 12, 12);
       try
       {
           User user = new User
           {
               gid = 1,
               cid = 1,
               firstName = model.firstName,
               lastName = model.lastName,
               email = model.email,
               username = model.username,
               password = model.password,
               creationDate = bla,
               active = 1
           };
           myContext.Users.AddObject(user);
           myContext.SaveChanges();

       }
       catch (Exception ex)
       {
           throw ex;
       }

       return View();               
   }

相應地傳輸這些值。使用者表:

[id] [int] IDENTITY(1,1) NOT NULL,
[cid] [int] NULL,
[gid] [int] NULL,
[firstName] [nvarchar](100) NOT NULL,
[lastName] [nvarchar](100) NOT NULL,
[email] [nvarchar](max) NOT NULL,
[username] [nvarchar](100) NOT NULL,
[password] [nvarchar](100) NOT NULL,
[creationDate] [datetime] NOT NULL,
[active] [int] NOT NULL,

約束 [PK_使用者_3213E83F0AD2A005] 主鍵集群

我刪除了所有外鍵以確保沒有任何影響。我很確定它在前一刻可以正常工作,但現在我無法弄清楚問題出在哪裡。它在執行 savechanges 時崩潰:

{"An error occurred while updating the entries. See the inner exception for details."}
{"The member with identity '' does not exist in the metadata collection.\r\nParameter name: identity"}

由於使用者表上的觸發器,問題正在重現。刪除它,問題不再重現。

當我嘗試使用 EF 插入時,我遇到了同樣的錯誤,錯誤是

The member with identity 'Id' does not exist in the metadata collection.\r\nParameter name: identity

一開始並不明顯,但異常消息非常簡潔,因為我的數據庫知道該列Id int,但在我的程式碼上為對象創建的屬性int ID返回命名映射,Id 未映射到 ID。

所以當一個帶有屬性的對像ID被發送到只知道你的數據庫時,Id你會得到上述錯誤。

我希望這會有所幫助,謝謝

引用自:https://stackoverflow.com/questions/10818730