0

I am currently looping through my Contact table and setting their IsCustomer flag to false using a foreach loop.

using (var db = new Entities(cs))
{
    foreach (var contact in db.Contacts)
        contact.IsCustomer = false;
    db.SaveChanges();
}

I notice that this process is taking a long time. Is there a way to set all my Contacts IsCustomer flag to false without setting them one by one? Or is there a faster way of doing this?

disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • 1
    You can execute update query directly for performance reason. using db.Database.ExecuteSqlCommand – Faizan Khan Aug 18 '15 at 11:34
  • The actual database update is going to be orders of magnitude more expensive than the time spent updating the in-memory objects. That portion is almost certainly negligible in this process. – Servy Aug 18 '15 at 13:06

2 Answers2

2

As suggested by @Jeroen Vannevel
Stackoverflow
this question would solve your problem hopefully,

Best is to use this
EntityFramework.Extended
but if you do not want to add this to your project then
you can use a simple SQL statement.
msdn

using (var context = new BloggingContext()) 
{ 
    context.Database.SqlCommand( 
        "UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1"); 
}
Community
  • 1
  • 1
Dragon
  • 1,078
  • 2
  • 9
  • 31
1
    using (Entities db = new Entities())
    {
        int changed = Entities.Database.ExecuteSqlCommand("Update Contact set IsCustomer = 0");
    }
Yissachar
  • 71
  • 5