[英]Update database instead of adding a row in MVC controller
I have code that is working to add new row into my site profile table but when someone tries to update the profile, I am not sure how to handle that. 我有代码正在努力将新行添加到我的网站配置文件表中,但当有人试图更新配置文件时,我不知道如何处理它。 I am updating multiple tables from the controller.
我正在从控制器更新多个表。
I have following code. 我有以下代码。 I check in customers table if ID is already present, if yes, then I change the state of entity to be modified.(I found this code online).
我检查客户表是否已经存在ID,如果是,那么我更改要修改的实体的状态。(我在网上找到了这个代码)。 I have commented out the next line because it was giving me an error.
我已经注释掉了下一行,因为它给了我一个错误。
This code does not throw any error on saving changes but it does not update the database. 此代码不会在保存更改时抛出任何错误,但不会更新数据库。
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();
I would like database to be updated with new object. 我想用新对象更新数据库。 These are my new objects with new data
这些是带有新数据的新对象
CustomerProfile obj = GetCustomerProfile();
ServiceProvider objSv = GetServiceProvider();`enter code here`
Problem is in the following line: 问题出在以下几行:
var oldCustomerServices = _context.CustomerServices;
Here _context.CustomerServices
is not a CustomerServices
object. 这里
_context.CustomerServices
不是CustomerServices
对象。 Its a DbSet
of CustomerService
but you are treating like a CustomerServices
object. 它是
CustomerService
的DbSet
,但您将其DbSet
CustomerServices
对象。
I think your code should be as follows: 我认为您的代码应如下所示:
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.