簡體   English   中英

更新數據庫而不是在MVC控制器中添加行

[英]Update database instead of adding a row in MVC controller

我有代碼正在努力將新行添加到我的網站配置文件表中,但當有人試圖更新配置文件時,我不知道如何處理它。 我正在從控制器更新多個表。

我有以下代碼。 我檢查客戶表是否已經存在ID,如果是,那么我更改要修改的實體的狀態。(我在網上找到了這個代碼)。 我已經注釋掉了下一行,因為它給了我一個錯誤。

此代碼不會在保存更改時拋出任何錯誤,但不會更新數據庫。

    var oldCustomer = _context.Customers.Find(objSv.CustomerServices.strUserID);
     var oldCustomerServices = _context.CustomerServices;

    if (oldCustomer == null) {
      _context.Customers.Add(obj);
      _context.CustomerServices.Add(objSv.CustomerServices);
        }
     else
     {
       _context.Entry(oldCustomer).State = EntityState.Modified;
 //  _context.Entry(oldCustomerServices).State = EntityState.Modified;
            }

   _context.SaveChanges();

我想用新對象更新數據庫。 這些是帶有新數據的新對象

        CustomerProfile obj = GetCustomerProfile();
        ServiceProvider objSv = GetServiceProvider();`enter code here`

問題出在以下幾行:

var oldCustomerServices = _context.CustomerServices;

這里_context.CustomerServices不是CustomerServices對象。 它是CustomerServiceDbSet ,但您將其DbSet CustomerServices對象。

我認為您的代碼應如下所示:

var oldCustomerServices = _context.CustomerServices.Find(CustomerServices.Id); // <-- I have assumed primary key name of `CustomerServices` is `Id`. If anything else then use that.

if(oldCustomerServices == null)
{
    CustomerServices newCustomerServices = new CustomerServices()
    {
      // Populate the customer service property here
    }
    _context.CustomerServices.Add(newCustomerServices);
} 
else
{
     _context.Entry(oldCustomerServices).State = EntityState.Modified;
}


var oldCustomer = _context.Customers.Find(objSv.CustomerServices.strUserID);

if (oldCustomer == null) 
{
   Customer newCustomer = new Customer()
   {
       // Populate the customer property here
   }

   _context.Customers.Add(newCustomer);
  _context.CustomerServices.Add(objSv.CustomerServices);
}
else
{
  _context.Entry(oldCustomer).State = EntityState.Modified;
}

_context.SaveChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM