I am using Entity Framework & LINQ to retrieve data. I am having a problem with the following:
var customer= db.customers.where(c=>c.id==1);
customer.name=santhosh;
customer.city=hyd;
The fields are changing in the database before I call:
db.SaveChanges();
How do I avoid this?
If you mean changing as in changing outside of application, changes in SQL Management Studio for example. Entity Framework cannot detect those changes, so as a result you might get stale objects that was cached by Entity Framework. To prevent receiving cached object and get the up-to-date values from database, use AsNoTracking.
Try putting AsNoTracking():
Or if your problem is to detect concurrent updates(unfortunate terminology, it doesn’t apply to UPDATE only) to same row, use rowversion(aka timestamp) field type; then on your .NET code add
Timestampattribute on the property. Example: http://www.ienablemuch.com/2011/07/entity-framework-concurrency-checking.htmlUPDATE (after your comment):
If you really has no intent to persist your object changes to database. Try detaching the object.
Try this:
That won’t save your changes on name and city to database.
If you want something more robust(the above will fail an exception if the object was not yet attached), create a helper:
To use:
Evict(yourDbContextHere, typeof(Product), "ProductId", 1);http://www.ienablemuch.com/2011/08/entity-frameworks-nhibernate.html