Reputation: 57
I use Entity Framework and stored procedures.
modelBuilder.Entity<MyModel>().MapToStoredProcedures();
I used Insert update and delete without any problem.but for some purpose I want to use AutoDetectChangesEnabled = false;
After that entity doesn't work anymore and nothing changes in the database after SaveChanges
. But when I comment AutoDetectChangesEnabled
or set it to true, it works fine.
This is my code: I read from Excel and import into database:
dt = exc.ReadExcel(address, ".xlsx");
using (var db = new Context())
{
db.Configuration.AutoDetectChangesEnabled = false;
for (int i = 1; i < dt.Rows.Count; i++)
{
int id = int.Parse(dt.Rows[i][0].ToString());
var thisChah = db.MyModel.Find(id);
if (thisChah == null)
{
continue;
}
thisChah.f1 = dt.Rows[i][1].ToString();
thisChah.f2 = dt.Rows[i][2].ToString();
thisChah.f3 = dt.Rows[i][3].ToString();
thisChah.f4 = dt.Rows[i][4].ToString();
thisChah.f5 = dt.Rows[i][5].ToString();
thisChah.f6 = dt.Rows[i][6].ToString();
thisChah.f7 = dt.Rows[i][7].ToString();
LogsAnyThing("row " + i + "- OK ");
if(i % 50 == 0)
{
int result = db.SaveChanges();
if (result > 0)
{
LogsAnyThing("row " + i + "- Added ");
}
}
}
db.SaveChanges();
}
Upvotes: 4
Views: 2633
Reputation: 987
Since you have turned off AutoDetectChanges , you need to explicitly tell context to look for any changes before attempting to call SaveChanges(). You can do this by adding this statement - db.ChangeTracker.DetectChange()
before call to db.SaveChanges(). Without this context is not aware that any changes has been done to the model.
You can read more @https://learn.microsoft.com/en-us/ef/ef6/saving/change-tracking/auto-detect-changes
Upvotes: 6