title: Entity Framework Null Reference When Adding New Record
body: <p>I currently have a project that uses Entity Framework 4.1 for logging to a database so we can track the web application which is deployed on more than one web server.  I built it using <a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx" rel="nofollow">Scott Gu's Code First</a> solution.</p>
  
  <p>So, I have code like this:</p>
  
  <pre><code>logging.Logs.Add(newLog);
  </code></pre>
  
  <p>which is <em>sometimes</em> throwing this error:</p>
  
  <blockquote>
    <p>System.NullReferenceException : Object reference not set to an
    instance of an object. at
    System.Data.Objects.ObjectStateManager.DetectConflicts(IList<code>1
    entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at
    System.Data.Entity.Internal.Linq.InternalSet</code>1.ActOnSet(Action action,
    EntityState newState, Object entity, String methodName) at
    System.Data.Entity.Internal.Linq.InternalSet<code>1.Add(Object entity) at
    System.Data.Entity.DbSet</code>1.Add(TEntity entity)</p>
  </blockquote>
  
  <p>Most of the time it works fine, but it will hiccup now and then.  Is there a best practice I should be aware of when I have more than one server using this code to access/write to the same database?</p>
  
  <p>The approach used right now is that each request causes the system to add several new log objects into the collection and then save a grouping of them, rather than save each individual log record.  Here's an outline of my class.</p>
  
  <pre><code>public class LoggingService : ILoggingService
  {
      Logging.Model.MyLogging logging;
  
      public LoggingService()
      {
          InitializeLog();
      }
  
      /// &lt;summary&gt;
      /// Save any pending log changes (only necessary if using the Add methods)
      /// &lt;/summary&gt;
      public void SaveChanges()
      {
          //ensure that logging is not null
          InitializeLog();
  
          logging.SaveChanges();
      }
  
      #region Private Methods
      private void InitializeLog()
      {
          if (logging == null)
              logging = new Model.MyLogging();
      }
  
      private void Log(Level level, int sourceId, string message, bool save, int? siteId = null, int? epayCustomerId = null, 
          string sessionId = null, int? eventId = null, Exception exception = null)
      {
          if (sourceId == 0)
              throw new ArgumentNullException("sourceId", "The Source Id cannot be null and must be valid.");
  
          var source = (from s in logging.Sources
                       where s.SourceId == sourceId
                       select s).FirstOrDefault();
  
          if (source == null)
              throw new ArgumentNullException("sourceId", String.Format("No valid source found with Id [{0}].", sourceId));
  
          if (eventId.HasValue)
          {
              if (eventId.Value &gt; 0)
              {
                  var code = (from e in logging.Events
                              where e.EventId == eventId.Value
                              select e).FirstOrDefault();
  
                  //if event id was passed in but no event exists, create a "blank" event
                  if (code == null)
                  {
                      Event newCode = new Event()
                      {
                          EventId = eventId.Value, 
                          Description = "Code definition not specified."
                      };
  
                      InitializeLog();
                      logging.Events.Add(newCode);
                      logging.SaveChanges();
                  }
              }
          }
  
          var newLog = new Log()
          {
              Created = DateTime.Now,
              Message = message,
              Source = source,
              Level = level,
              EventId = eventId,
              SessionId = sessionId,
              SiteId = siteId,
              MachineName = System.Environment.MachineName,
          };
  
          if (exception != null)
              newLog.Exception = String.Format("{0}{1}{2}{1}", exception.Message, Environment.NewLine, exception.StackTrace);
  
          //ensure that the logging is not null
          InitializeLog();
  
          logging.Logs.Add(newLog);
  
          if (save)
          {
              logging.SaveChanges();
          }
      }
  
      #endregion
  
  }
  </code></pre>
  
  <p>I am using IoC with StructureMap, and I did not initialize this class as a singleton.</p>
  
  <pre><code>For&lt;ILoggingService&gt;().Use&lt;LoggingService&gt;();
  </code></pre>
  
  <p>And my context class looks like this:</p>
  
  <pre><code>internal class MyLogging : DbContext
  {
      public DbSet&lt;Source&gt; Sources { get; set; }
      public DbSet&lt;Event&gt; Events { get; set; }
      public DbSet&lt;Log&gt; Logs { get; set; }
  
      /// &lt;summary&gt;
      /// DO NOT ADD ITEMS TO THIS COLLECTION
      /// &lt;/summary&gt;
      public DbSet&lt;LogArchive&gt; LogArchives { get; set; }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          Database.SetInitializer(new MyDbContextInitializer());
  
          modelBuilder.Entity&lt;Event&gt;().Property(p =&gt; p.EventId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
  
          modelBuilder.Entity&lt;Source&gt;().Property(p =&gt; p.SourceId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
  
          modelBuilder.Entity&lt;LogArchive&gt;().Property(p =&gt; p.LogId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
  
          base.OnModelCreating(modelBuilder);
      }
  
      //public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges&lt;MyLogging&gt;
      public class MyDbContextInitializer : CreateDatabaseIfNotExists&lt;MyLogging&gt;
      {
          protected override void Seed(MyLogging dbContext)
          {
              // seed data
  
              base.Seed(dbContext);
          }
      }
  }
  </code></pre>
  
  <p>I'm probably doing something obviously wrong, but I just don't see it.</p>
  
  <p><strong>EDIT:</strong>
  As requested, here is a sample of how I call the logging service code.  This particular method is logging information related to the HTTP Request.  I append the the log items in one try catch and save in a separate try catch so if there is an issue it will at least save the additions that took.  The handler is another service injected into this class through IoC that sends the details of the error to me via e-mail.</p>
  
  <p>A single post to the server could log as many as 50-70 separate details separated into chunks of 10-15 (http request, data sent to a web service, result of the web service call, response back to the client), which is why I want to add a grouping and then save the grouping, rather than open and close a connection with each individual item.</p>
  
  <pre><code>public void LogHttpPostStart(HttpPostRequest request)
  {
          try
          {
              //if no session is set, use the ASP.NET session
              request.SessionId = GetSessionId(request.SessionId);
              int eventId = (int)Model.Enums.Logging.Event.SubmittedByClient;
  
              var current = HttpContext.Current;
  
              if (current != null)
              {
                  logService.AddDebug((int)request.Source, String.Format("{0}  HTTP Request Details  {0}", Header2Token.ToString().PadRight(HeaderTokenCount, Header2Token)),
                      siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                      eventId: eventId);
  
                  //Server Information
                  logService.AddDebug((int)request.Source, String.Format("Machine Name: {0}", current.Server.MachineName),
                      siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                      eventId: eventId);
  
                  //User Information
                  logService.AddDebug((int)request.Source, String.Format("User Host Address: {0}", current.Request.UserHostAddress),
                      siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                      eventId: eventId);
                  logService.AddDebug((int)request.Source, String.Format("User Host Name: {0}", current.Request.UserHostName),
                      siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                      eventId: eventId);
  
                  //Browser Information
                  if (current.Request.Browser != null)
                  {
                      logService.AddDebug((int)request.Source, String.Format("Browser: {0}", current.Request.Browser.Browser),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
                      logService.AddDebug((int)request.Source, String.Format("Browser Version: {0}", current.Request.Browser.Version),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
                      logService.AddDebug((int)request.Source, String.Format("User Agent: {0}", current.Request.UserAgent),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
                      logService.AddDebug((int)request.Source, String.Format("Is Mobile Device: {0}", current.Request.Browser.IsMobileDevice.ToString()),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
  
                      if (current.Request.Browser.IsMobileDevice)
                      {
                          logService.AddDebug((int)request.Source, String.Format("Mobile Device Manufacturer: {0}", current.Request.Browser.MobileDeviceManufacturer),
                              siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                              eventId: eventId);
                          logService.AddDebug((int)request.Source, String.Format("Mobile Device Model: {0}", current.Request.Browser.MobileDeviceModel),
                              siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                              eventId: eventId);
                      }
  
                      logService.AddDebug((int)request.Source, String.Format("Platform: {0}", current.Request.Browser.Platform),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
                      logService.AddDebug((int)request.Source, String.Format("Cookies Enabled: {0}", current.Request.Browser.Cookies.ToString()),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
                      logService.AddDebug((int)request.Source, String.Format("Frames Enabled: {0}", current.Request.Browser.Frames.ToString()),
                          siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                          eventId: eventId);
  
                      if (current.Request.Browser.JScriptVersion != null)
                      {
                          logService.AddDebug((int)request.Source, String.Format("Javascript Version: {0}", current.Request.Browser.JScriptVersion.ToString()),
                              siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                              eventId: eventId);
                      }
  
                  }
  
                  logService.AddDebug((int)request.Source, String.Format("{0}  End HTTP Request Details  {0}", Header2Token.ToString().PadRight(HeaderTokenCount, Header2Token)),
                      siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
                      eventId: eventId);
              }
          }
          catch (Exception ex)
          {
              handler.HandleError(true, ex);
          }
  
          try
          {
              logService.SaveChanges();
          }
          catch (Exception ex)
          {
              handler.HandleError(true, ex);
          }
      }
  </code></pre>