When do I want to have tracking enabled and when I want it disabled in a WebAPI? It almost seems like I would always want to use this:
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
with my DbContext and only when I need to persist an object I would mark the object as modified. Could you give me a specific example when I need to have tracking enabled and when I want it to be disabled?
Thanks
First Let's understand what exactly is tracking , this is a good reading about it but in short :
Tracking behavior controls if Entity Framework Core will keep
information about an entity instance in its change tracker. If an
entity is tracked, any changes detected in the entity will be
persisted to the database during SaveChanges().
var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1);
blog.Rating = 5;
context.SaveChanges();
as you can see in the above example if the query is tracked (which is default behavior) you don't even need to mark the object as modified , because this object is retrieved by the context it's attached to it and the context will notice changes preformed on it and persist it we SaveChanges() is called
So to answer your questions: it depends on the scenario ,if you are sure that you will not modify the retrieved data and won't need to persist any changes that you might perform on it then there is no point in using a tracked query , in fact it would benefit the performance if you used a No-Tracking query .
Think of No-Tracking queries as read-only data that you just want to retrieve to display to the user or extract some info from it
the mentioned articular talks about EF core but the tracking vs no-tracking concept are the same even in other ORMs
WebAPI will always have NoTracking.
Tracking is required when you do a fetch and then you make changes(updates) to the same object that was fetched. Now if you save that object back to DB, then tracking makes sense.
This is never the case in WebAPI.
The only context instances I use QueryTrackingBehavior.NoTracking are Reporting contexts, not API contexts unless the API applicable to that context is entirely read-only.
NoTracking will provide a nominal speed boost for data Read operations.
You can use NoTracking for update operations, but you will require a bit of additional code, and incur a nominal penalty for Updates. If you are building an Append-only (Inserts, no Updates) then NoTracking provides no penalty.
Why: When EF loads an entity with tracking, 2 things happen. First, the reference is loaded into the local cache. Second, a proxy is used which keeps track of updates against fields on the entity.
Given an update accepting a new Message for a Record entity:
void UpdateMessage(int recordId, string message);
With tracking:
void UpdateMessage(int recordId, string message)
{
using(var context = new AppContext())
{
var record = context.Records.Single(x => x.RecordId == recordId);
record.Message = message;
context.SaveChanges();
}
}
Without tracking:
void UpdateMessage(int recordId, string message)
{
using(var context = new AppContext())
{
var record = context.Records.AsNoTracking().Single(x => x.RecordId == recordId);
record.Message = message;
context.Update(record); // or Attach() and set Modified state.
context.SaveChanges();
}
}
These look very similar on the surface, but there is a distinct difference that will happen under the hood:
In the first case, EF will generate an SQL statement similar to:
UPDATE tblRecords SET Message = #1 WHERE RecordId = #0
In the second case, EF will generate:
UPDATE tblRecords SET Message = #1, SomeField = #2, SomeOtherField = #3, CreatedAt = #4, CreatedBy = #5 WHERE RecordId = #0
When taking untracked entities and "Updating" them, EF has no idea what changed, so every column is updated. With tracking, only fields that were updated will be in the query. For larger entities this can be noticeable.
Inserts, including for append-only systems aren't affected since these would include all columns anyways.
If you are projecting to viewmodels and/or sending over-the-wire, etc... tracking will not have a difference, and is a slight performance hit.
If you are doing more complicated queries where you are pulling data into memory and mutating it, then tracking makes more sense as it allows you to modify an entity and call SaveChanges again.
It's as simple as that.
I am using entity framework 5.0. I am in a rocess od changing my app from ObjectContext to DbContext model. DbContext should be according to microsoft the recommended approach. I use database forst approach and I have generated model form database.
But, at a very first simple task there is a problem. Namely simple update of a record is broken.
Let's have a simple table Item, for ilustration only:
Item
(
ItemId int NOT NULL, -- Primary key
Name nvarchar(50) NOT NULL,
Description NVARCHAR(50)
)
I have noticed that using DbContext does not support updating a record not as ObjectContext does.
In my application I have a simple update method.
public void UpdateItem()
{
MyContext context = new MyContext();
Item item = new Item();
item.ItemId = 666;
context.Items.Attach(item);
// From this point onward EF tracks the changes I make to Item
Item.Description = "Some description";
context.SaveChanges();
}
Using ObjectContext this method correctly updates a record. Using SQL profiler I can see that it generates something like this (greatly simplified!!!)
UPDATE Item
SET Description = 'Some description'
WHERE ItemId = 666
If, however I try to do the same thing in DbContext I get the exception:
System.Exception: Items.aspx.cs - logged from CustomError() ---> System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
And no database UPDATE is issued to Sql server.
I guess that DbContext validates all the properties and the property Name is null. This by design. I do not intend to modify it, I do not even know what is it and I do not need to know what is it.
Only the property Description was changed. Clearly ObjectContext does not track changes correctly.
How can this problem be resolved?
I have researched the issue and found the something on updating records.
For example this link: https://stackoverflow.com/a/15339512/4601078
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();
But this is horrible code. For every property on should add a line like:
entry.Property(e => e.Email).IsModified = true;
This produces ugly unreadable code, an I suspect lamda expression are not stelar in performance.
Even worse are those who propose to make a roundtrip to DB to fetch existing records with all properties populated, update it and the save changes. This is a no go with regard to performance.
So, how to tackle with simple entity updates or is this DbContext just another item in microsofts collection of dead ends which serve no real purpose?
DbContext doesn't really track changes by watching properties, it compares the values to previously known values. And validation always works on the entire entity so the only real choice if you want to do things this way is to disable validation during this operation. See Entity Framework validation with partial updates
If you know for sure that the changes you apply are valid, or you have custom code to validate them, you can turn off validation by EF altogether:
db.Configuration.ValidateOnSaveEnabled = false;
This works OK as long as you do it your way: attach a new entity with a known Id (aka a stub entity) and then modify its properties. EF will only update the properties it detects as having been modified (indeed by comparing original and current values, not, as ObjectContext did, by change notifications). You shouldn't mark the entity itself as modified.
If you don't want to turn off EF's validation, but neither want to mark individual properties as modified, I think this could be a useful alternative (brought to my attention by Alex's answer).
Is there a best practice for doing a copy of an entity, making some changes to it based on user input, and then re-inserting it into the database?
Some other Stackoverflow threads have mentioned that EF will handle inserting new objects for you even if the same primary key exists in the database, but I'm not quite sure that's how EF Core is handling it. Whenever I try and copy an object I get an error of
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
Basically I just need a clean way to copy an object, make some changes to it based on user input, and then insert that copy back into the database, and have the Id auto-increment properly. Is there a best practice or simple way of doing this without having to manually set properties to null or empty?
EDIT: Example code for retrieving the object from the database:
public Incident GetIncidentByIdForCloning(int id)
{
try
{
return _context.Incident.Single(i => i.IncidentId == id);
}
catch
{
return null;
}
}
Code after retrieving object (As some fields are auto-generated like RowVersion which is a Timestamp):
public IActionResult Clone([FromBody]Incident Incident)
{
var incidentToCopy = _incidentService.IncidentRepository.GetIncidentByIdForCloning(Incident.IncidentId);
incidentToCopy.IncidentTrackingRefId = _incidentService.IncidentRepository.GetNextIdForIncidentCategoryAndType(
Incident.IncidentCategoryLookupTableId, Incident.IncidentTypeLookupTableId).GetValueOrDefault(0);
incidentToCopy.RowVersion = null;
incidentToCopy.IncidentId = 0; //This will fail with or without this line, this was more of a test to see if manually setting would default the insert operation, such as creating a brand new object would normally do.
incidentToCopy.IncidentCategoryLookupTableId = Incident.IncidentCategoryLookupTableId;
incidentToCopy.IncidentTypeLookupTableId = Incident.IncidentTypeLookupTableId;
var newIncident = _incidentService.IncidentRepository.CreateIncident(incidentToCopy);
...
I realize I could just make an entirely new object and do left-hand copying, but that seems terribly inefficient and I want to know if EF Core offers better solutions.
So I went through the "Possible duplicate" thread a bit more than I did when I initially stumbled upon it before creating this one, and there was a not-so-highly upvoted solution that I overlooked that essentially just grabs all of the values at once when retrieving the object from the database - and it doesn't retrieve a reference to that object in the process. My code now looks something like this:
try
{
var incidentToCopy = _context.Incident.Single(i => i.IncidentId == id);
return (Incident) _context.Entry(incidentToCopy).CurrentValues.ToObject();
}
In your IncidentRepository class try getting the Incident by using AsNoTracking and it should get tracked as a new entity when it is added.
public void Clone(int id)
{
// Prevent tracking changes to the object.
var incident = _context.AsNoTracking().SingleOrDefault(i => i.Id == id);
// Setting back to 0 should treat the object Id as unset.
incident.Id = 0;
// Add the Incident while it is untracked will treat it as a new entity.
_context.Incidents.Add(incident);
_context.SaveChanges();
}
I believe what is happening here is the following:
When you retrieve a value from the database, it gets stored in something like
context.ChangeTracker.Entries<Incident>
Which is a collection of Incident entries being tracked. When you change the id property of the incident object you've retrieved you are sort of abusing the ChangeTracker in the name of efficiency. The ChangeTracker does not believe you have created a new object. You might be able to try something like finding the entry in the ChangeTracker and set it's state to detached then after you've set the id to 0 add the object back to the context.DbSet but at that point you have probably made things way more complicated than simply copying the object.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am using Entity Framework to populate a grid control. Sometimes when I make updates I get the following error:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I can't figure out how to reproduce this. But it might have something to do with how close together I make the updates. Has anyone seen this or does anyone know what the error message refers to?
Edit: Unfortunately I am no longer at liberty to reproduce the problem I was having here, because I stepped away from this project and don't remember if I eventually found a solution, if another developer fixed it, or if I worked around it. Therefore I cannot accept any answers.
I ran into this and it was caused by the entity's ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity's ID has been set.
From Paul Bellora's comment
I had this exact issue, caused by forgetting to include the hidden ID
input in the .cshtml edit page
That's a side-effect of a feature called optimistic concurrency.
Not 100% sure how to turn it on/off in Entity Framework but basically what it's telling you is that between when you grabbed the data out of the database and when you saved your changes someone else has changed the data (Which meant when you went to save it 0 rows actually got updated). In SQL terms, their update query's where clause contains the original value of every field in the row, and if 0 rows are affected it knows something's gone wrong.
The idea behind it is that you won't end up overwriting a change that your application didn't know has happened - it's basically a little safety measure thrown in by .NET on all your updates.
If it's consistent, odds are it's happening within your own logic (EG: You're actually updating the data yourself in another method in-between the select and the update), but it could be simply a race condition between two applications.
Wow, lots of answers, but I got this error when I did something slightly different that no on else has mentioned.
Long story short, if you create a new object and tell EF that its modified using the EntityState.Modified then it will throw this error as it doesn't yet exist in the database. Here is my code:
MyObject foo = new MyObject()
{
someAttribute = someValue
};
context.Entry(foo).State = EntityState.Modified;
context.SaveChanges();
Yes, this seems daft, but it arose because the method in question used to have foo passed to it having been created earlier on, now it only has someValue passed to it and creates foo itself.
Easy fix, just change EntityState.Modified to EntityState.Added or change that whole line to:
context.MyObject.Add(foo);
I was facing this same scaring error... :) Then I realized that I was forgetting to set a
#Html.HiddenFor(model => model.UserProfile.UserId)
for the primary key of the object being updated! I tend to forget this simple, but very important thingy!
By the way: HiddenFor is for ASP.NET MVC.
Check whether you forgot the "DataKeyNames" attribute in the GridView.
it's a must when modifying data within the GridView
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx
The issue is caused by either one of two things :-
You tried to update a row with one or more properties are Concurrency Mode: Fixed .. and the Optimistic Concurrency prevented the data from being saved. Ie. some changed the row data between the time you received the server data and when you saved your server data.
You tried to update or delete a row but the row doesn't exist. Another example of someone changing the data (in this case, removing) in between a retrieve then save OR you're flat our trying to update a field which is not an Identity (ie. StoreGeneratedPattern = Computed) and that row doesn't exist.
I got this same error because part of the PK was a datetime column, and the record being inserted used DateTime.Now as the value for that column. Entity framework would insert the value with millisecond precision, and then look for the value it just inserted also with millisecond precision. However SqlServer had rounded the value to second precision, and thus entity framework was unable to find the millisecond precision value.
The solution was to truncate the milliseconds from DateTime.Now before inserting.
I was having same problem and #webtrifusion's answer helped find the solution.
My model was using the Bind(Exclude) attribute on the entity's ID which was causing the value of the entity's ID to be zero on HttpPost.
namespace OrderUp.Models
{
[Bind(Exclude = "OrderID")]
public class Order
{
[ScaffoldColumn(false)]
public int OrderID { get; set; }
[ScaffoldColumn(false)]
public System.DateTime OrderDate { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Username { get; set; }
}
}
I had the same problem, I figure out that was caused by the RowVersion which was null.
Check that your Id and your RowVersion are not null.
for more information refer to this tutorial
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
I also came across this error. The problem it turned out was caused by a Trigger on the table I was trying to save to. The Trigger used 'INSTEAD OF INSERT' which means 0 rows ever got inserted to that table, hence the error. Luckily in may case the trigger functionality was incorrect, but I guess it could be a valid operation that should somehow be handled in code. Hope this helps somebody one day.
While editing include the id or primary key of the entity as a hidden field in the view
ie
#Html.HiddenFor(m => m.Id)
that solves the problem.
Also if your model includes non-used item include that too and post that to the controller
I started getting this error after changing from model-first to code-first. I have multiple threads updating a database where some might update the same row. I don't know why I didn't have a problem using model-first, assume that it uses a different concurrency default.
To handle it in one place knowing the conditions under which it might occur, I added the following overload to my DbContext class:
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
public class MyDbContext: DbContext {
...
public int SaveChanges(bool refreshOnConcurrencyException, RefreshMode refreshMode = RefreshMode.ClientWins) {
try {
return SaveChanges();
}
catch (DbUpdateConcurrencyException ex) {
foreach (DbEntityEntry entry in ex.Entries) {
if (refreshMode == RefreshMode.ClientWins)
entry.OriginalValues.SetValues(entry.GetDatabaseValues());
else
entry.Reload();
}
return SaveChanges();
}
}
}
Then called SaveChanges(true) wherever applicable.
The line [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)] did the trick in my case:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int? SomeNumber { get; set; }
You need to explicitly include a BoundField of the primary key. If you don't want the user to see the primary key, you have to hide it via css:
<asp:BoundField DataField="Id_primary_key" ItemStyle-CssClass="hidden"
HeaderStyle-CssClass="hidden" />
Where 'hidden' is a class in css that has it's display set to 'none'.
I came across this issue on a table that was missing a primary key and had a DATETIME(2, 3) column (so the entity's "primary key" was a combination of all the columns)... When performing the insert the timestamp had a more precise time (2018-03-20 08:29:51.8319154) that was truncated to (2018-03-20 08:29:51.832) so the lookup on key fields fails.
Just make sure table and form both have primary key and edmx updated.
i found that any errors during update were usually because of:
- No primary key in Table
- No primary key in Edit view/form (e.g. #Html.HiddenFor(m=>m.Id)
I also had this error. There are some situations where the Entity may not be aware of the actual Database Context you are using or the Model may be different. For this, set: EntityState.Modified; to EntityState.Added;
To do this:
if (ModelState.IsValid)
{
context.Entry(yourModelReference).State = EntityState.Added;
context.SaveChanges();
}
This will ensure the Entity knows youre using or adding the State youre working with. At this point all the correct Model Values need to be set. Careful not to loose any changes that may have been made in the background.
Hope this helps.
#Html.HiddenFor(model => model.RowVersion)
My rowversion was null, so had to add this to the view
which solved my issue
public void Save(object entity)
{
using (var transaction = Connection.BeginTransaction())
{
try
{
SaveChanges();
transaction.Commit();
}
catch (OptimisticConcurrencyException)
{
if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Deleted || ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Modified)
this.Refresh(RefreshMode.StoreWins, entity);
else if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Added)
Detach(entity);
AcceptAllChanges();
transaction.Commit();
}
}
}
I had the same problem.
In my case I was trying to update the primary key, which is not allowed.
I got this error sporadically when using an async method. Has not happened since I switched to a synchronous method.
Errors sporadically:
[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public async Task<IHttpActionResult> Delete(int id, int customerId)
{
var file = new Models.File() { Id = id, CustomerId = customerId };
db.Files.Attach(file);
db.Files.Remove(file);
await db.SaveChangesAsync();
return Ok();
}
Works all the time:
[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public IHttpActionResult Delete(int id, int customerId)
{
var file = new Models.File() { Id = id, CustomerId = customerId };
db.Files.Attach(file);
db.Files.Remove(file);
db.SaveChanges();
return Ok();
}
I got that error when I was deleting some rows in the DB (in the loop), and the adding the new ones in the same table.
The solutions for me was, to dynamicaly create a new context in each loop iteration
This will also happen if you are trying to insert into a unique constraint situation, ie if you can only have one type of address per employer and you try to insert a second of that same type with the same employer, you will get the same problem.
OR
This could also happen if all of the object properties that were assigned to, they were assigned with the same values as they had before.
using(var db = new MyContext())
{
var address = db.Addresses.FirstOrDefault(x => x.Id == Id);
address.StreetAddress = StreetAddress; // if you are assigning
address.City = City; // all of the same values
address.State = State; // as they are
address.ZipCode = ZipCode; // in the database
db.SaveChanges(); // Then this will throw that exception
}
I got this exception when attaching an object that didn't exist in the database. I had assumed the object was loaded from a separate context, but if it was the user's first time visiting the site, the object was created from scratch. We have auto-incrementing primary keys, so I could replace
context.Users.Attach(orderer);
with
if (orderer.Id > 0) {
context.Users.Attach(orderer);
}
Well i have this same issue. But this was due to my own mistake. Actually i was saving an object instead of adding it. So this was the conflict.
One way to debug this problem in an Sql Server environment is to use the Sql Profiler included with your copy of SqlServer, or if using the Express version get a copy of Express Profiler for free off from CodePlex by the following the link below:
Express Profiler
By using Sql Profiler you can get access to whatever is being sent by EF to the DB. In my case this amounted to:
exec sp_executesql N'UPDATE [dbo].[Category]
SET [ParentID] = #0, [1048] = NULL, [1033] = #1, [MemberID] = #2, [AddedOn] = #3
WHERE ([CategoryID] = #4)
',N'#0 uniqueidentifier,#1 nvarchar(50),#2 uniqueidentifier,#3 datetime2(7),#4 uniqueidentifier',
#0='E060F2CA-433A-46A7-86BD-80CD165F5023',#1=N'I-Like-Noodles-Do-You',#2='EEDF2C83-2123-4B1C-BF8D-BE2D2FA26D09',
#3='2014-01-29 15:30:27.0435565',#4='3410FD1E-1C76-4D71-B08E-73849838F778'
go
I copy pasted this into a query window in Sql Server and executed it. Sure enough, although it ran, 0 records were affected by this query hence the error being returned by EF.
In my case the problem was caused by the CategoryID.
There was no CategoryID identified by the ID EF sent to the database hence 0 records being affected.
This was not EF's fault though but rather a buggy null coalescing "??" statement up in a View Controller that was sending nonsense down to data tier.
None of the above answers quite covered my situation and the solution to it.
Code where the error was thrown in MVC5 controller:
if (ModelState.IsValid)
{
db.Entry(object).State = EntityState.Modified;
db.SaveChanges(); // line that threw exception
return RedirectToAction("Index");
}
I received this exception when I was saving an object off an Edit view. The reason it threw it was because when I went back to save it, I had modified the properties that formed the primary key on the object. Thus, setting its state to Modified didn't make any sense to EF - it was a new entry, not a previously saved one.
You can solve this by either A) modifying the save call to Add the object, or B) just don't change the primary key on edit. I did B).
When the accepted answer said "it won't end up overwriting a change that your application didn't know has happened", I was skeptic because my object was newly created. But then it turns out, there was an INSTEAD OF UPDATE, INSERT- TRIGGER attached to the table which was updating a calculated column of the same table.
Once I change this to AFTER INSERT, UPDATE, it was working fine.
This happened to me due to a mismatch between datetime and datetime2. Strangely, it worked fine prior to a tester discovering the issue. My Code First model included a DateTime as part of the primary key:
[Key, Column(Order = 2)]
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;
The generated column is a datetime column. When calling SaveChanges, EF generated the following SQL:
-- Region Parameters
DECLARE #0 Int = 2
DECLARE #1 Int = 25
DECLARE #2 Int = 141051
DECLARE #3 DateTime2 = '2017-07-27 15:16:09.2630000' --(will not equal a datetime value)
-- EndRegion
UPDATE [dbo].[OrganizationSurvey]
SET [OrganizationSurveyStatusId] = #0
WHERE ((([SurveyID] = #1) AND ([OrganizationID] = #2)) AND ([PurchasedDate] = #3))
Because it was trying to match a datetime column with a datetime2 value, it returned no results. The only solution I could think of was to change the column to a datetime2:
[Key, Column(Order = 2, TypeName = "DateTime2")]
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;
If you are trying to create mapping in your edmx file to a "function Imports", this can result this error. Just clear the fields for insert, update and delete that is located in Mapping Details for a given entity in your edmx, and it should work.
I hope I made it clear.
I have the following Model
public class CourseModel
{
[Key]
public int courseID { get; set; }
...
public virtual ICollection<CourseMeetModel> meets { get; set; }
}
When I try to edit one of the entries and if the input is valid it works fine.
However if the if its not valid it alerts the user of the mistakes. Once the user fixes the mistakes and tries to save i get the following exception.
Store update, insert, or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded. Refresh ObjectStateManager entries.
I have noticed this happens if the input fails the validation steps in my controller.
My Controller
public ActionResult EditCourseConfirmed(CourseModel course)
{
CoursesDBContext db = new CoursesDBContext();
bool valid = validateCouse(course); //If this fails and the course model is returned back to the view I get that error
if (valid)
{
try
{
db.Entry(course).State = EntityState.Modified;
db.SaveChanges();
Session[d.s_Clear] = false;
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, "Unable to save the course, please try again." + e.Message);
return View(course);
}
}
return View(course);
}
Try this
try {
context.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
context.Refresh(RefreshMode.ClientWins, db.table);
context.SaveChanges();
}
Props: https://stackoverflow.com/a/6848729/1166147
Adding on to explain, per your comments. Thanks for your EF4 CTP5 tip. Glad this fixed it, please mark as accepted. When you get this error, something happened that changed the data (another user, etc) between load and update, there is a trigger causing problems, or if using a stored procedure it hit 0 recs. It is hard to know without more info. Is this the first update hit? Was there another update run first that succeeded before the user hit the error, modified, and then tried to go on without refreshing? Do you have any triggers? What is your degree of concurrency - did another user edit and save between this users' query and update? Read the link to the post I gave - someone mentioned a ReadOnlyAttribute in an entity key's metadata being replaced, which causes its value to become zero as a potential cause - I am not sure about this, but it makes sense -
(Modified from MSDN) By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated, creating the potential for this error if another user modified the data. When this attribute is used, the Entity Framework checks for changes in the database before saving changes.
Any conflicting changes will cause an OptimisticConcurrencyException.
An OptimisticConcurrencyException can also occur when you define an Entity Data Model that uses stored procedures to make updates to the data source. In this case, the exception is raised when the stored procedure that is used to perform updates reports that zero rows were updated. SET NOCOUNT ON would fix thia.
Thanks to user #user1166147 it was causing a dbupdate exception though I still don't know why ...
Since EF4 CTP5 DbContext doesnt have a refresh method i ended up doing this:
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException e)
{
var entry = e.Entries.Single();
entry.OriginalValues.SetValues(entry.CurrentValues);
entry.CurrentValues.SetValues(entry.CurrentValues);
db.SaveChanges();
}
some more details here http://blogs.msdn.com/b/adonet/archive/2011/02/03/using-dbcontext-in-ef-feature-ctp5-part-9-optimistic-concurrency-patterns.aspx
In your view make sure to add this
#Html.HiddenFor(m => m.courseID)
I got the exception Reason was my entity has a Key with a mapping of
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
and when i added a new Entity and supplied an id, at save time the context will think it is a modified Entity and not a new one, so i did not supply a value to the Key and at save time i check for the keys default value, from this i know if its new or modified