繁体   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