Hi guys,
I'm having a "tearing my hair out and considering moving back to NHibernate" moment with EntityFramework 6 and a code-first model, with a MySQL database.
Essentially, I have a model as such:
public class MyModel
{
[Key, Column("ID")]
public int ID { get; set; }
[Column("ADDED")]
public DateTime Added { get; set; }
[ForeignKey("MySecondModelID")]
public virtual MySecondModel { get; set; }
[Column("MYSECONDMODELID")]
public int? MySecondModelID { get; set; }
}
The table column "MYSECONDMODELID" is nullable, therefore the record is not required. It's an optional child to be included if provided.
I'm essentially creating a new instance of the model and attempting to save it to the database like so:
using (var context = new MyDbContext())
{
var model = new MyModel()
{
Added = DateTime.Now,
MySecondModel = null
};
context.MyModels.Add(model);
context.SaveChanges();
}
But I keep receiving the same exception with the error message:
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded."
Obviously I have Googled the mother-loving junk out of this particular error, and every single result leads me to the same methodology to cure the problem: refresh the current context before attempting to save the changes.
So, this I have done by doing the following:
try
{
context.SaveChanges();
}
catch (Exception exception)
{
var context = ((IObjectContextAdapter)context).ObjectContext;
context.Refresh(RefreshMode.StoreWins, model);
context.SaveChanges();
}
But the same exception is always raised. No matter what I do, I cannot get that error to go away. Is there a way to disable concurrency checking within EntityFramework? I sense that most of my problems would dissipate if I could eliminate the checks.
I should point out that I have tried around 8 different solutions suggested through Google results. These include the above context refresh, as well as setting the exception's OriginalValues to the current values.
Can anybody possibly point out where I might be going wrong?
Thanks!
What I have tried:
Refreshing the database context before saving
Setting the current entity OriginalValues to CurrentValues before saving
Googled for the cause of the issue up to 10 pages deep into Google.