Reputation: 2237
I'm trying to update Entity/model using LINQ to SQL (DBML). but I'm not able to do it.
Here is my code snippet.
public void Update(Customer customer)
{
using (MyDataContext db = new MyDataContext())
{
db.Customers.Attach(customer, true);
db.SubmitChanges();
}
}
public Customer GetByID(int ID)
{
using (MyDataContext db = new MyDataContext())
{
return db.Customers.FirstOrDefault(c => c.CustomerID == ID);
}
}
My scenario is: I get the customer object and bind the customer object to form. and after change the form input data. Data is perfectly change but when I call update method. It's not updating it and I have this error:
An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
I searched a lots of internet but I'm not able to find any appropriate solution. I also modified my update function like that:
public void Update(Customer customer)
{
using (MyDataContext db = new MyDataContext())
{
var originalCustomer = db.Customers.FirstOrDefault(c => c.CustomerID == customer.CustomerID);
db.Customers.Attach(customer, originalCustomer);
db.SubmitChanges();
}
}
But still getting the same error.
I don't want to get Customer from database and update it properties from parameter customer properties. I want to use the same parameter customer and update it in database.
Please help me. Thanks!
Upvotes: 0
Views: 1436
Reputation:
The issue is you have two using statements, giving 2 different context The easier option would be to inject it into the controller and use it when needed
Upvotes: 0
Reputation: 1095
The problem is that even though you are using the same DbContext class you are using different DbContext objects because you are using two different "using" statements.
It's important that you use the same DbContext object throughout the request (assuming it's an MVC app).
The usual approach would be to instantiate the DbContext in the controller (or using Dependency Injection ) and use the reference everywhere.
Upvotes: 0
Reputation: 755
public void Update(Customer customer)
{
using (MyDataContext db = new MyDataContext())
{
var originalCustomer = db.Customers.Where(c => c.CustomerID == customer.CustomerID).FirstOrDefault();
// change the originalCustomer's properties with customer's properties.
db.SubmitChanges();
}
}
Upvotes: -1