Search code examples
c#entity-framework-6updatemodel

Entity Framework - explain my code


Is this a correct understanding of what this code does - and is it the correct way to update a row which has a URLPath of url so that the IsInProcessing column is true?

I haven't actually tried this code yet. Before I do, I want to try and understand it! It is pieced together from various sources.

The code:

using(var db = new DamoclesEntities())
{
    var urls = db.URLS;
    var result = urls.FirstOrDefault(u => u.URLPath == url);
    result.IsInProcessingQueue = true;
    db.SaveChanges();
}
  1. What I think is happening here is within the using I am instantiating the DamoclesEntities() class as var db.
  2. I then instantiate the db.URLS (class / table) to the var urls.
  3. I then find the first row where the URLPath (column) contains url, and that row is assigned to result.
  4. I change that row's IsInProcessingQueue (column value) to true;
  5. Finally, I save the changes to the database.

Solution

  • it is almost correct, but keep in mind, that FirstOrDefault will return null value in case if there is no rows found by specified criteria - URLPath == url.

    So in this case next row will produce NullReferenceException.

    Just add check of result for a null and do result.IsInProcessingQueue = true;db.SaveChanges(); only if result != null