【问题标题】:Update database instead of adding a row in MVC controller更新数据库而不是在 MVC 控制器中添加一行
【发布时间】:2019-09-22 11:09:10
【问题描述】:

我的代码正在将新行添加到我的站点配置文件表中,但是当有人尝试更新配置文件时,我不确定如何处理。我正在从控制器更新多个表。

我有以下代码。如果 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`

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework model-view-controller


    【解决方案1】:

    问题出在下面一行:

    var oldCustomerServices = _context.CustomerServices;
    

    这里的_context.CustomerServices 不是CustomerServices 对象。它是 CustomerService 中的 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();
    

    【讨论】:

    • 我尝试了上述方法,但仍然没有更新数据库。我删除了客户服务部分,只尝试使用 _context.Entry(oldCustomer).State = EntityState.Modified; 更新 oldCustomer }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多