title: Entity Framework : how to catch any error
body: <p>I am trying to insert data into a SQL Server table that has a lot of <code>not null</code> constraints:</p>
  
  <pre><code>CREATE TABLE [dbo].[Customer]
  (
      [CustomerId] [int] IDENTITY(1,1) NOT NULL,
      [FirstName] [varchar](255) NOT NULL,
      [LastName] [varchar](255) NOT NULL,
      [AddressLine] [varchar](255) NOT NULL
      CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ([CustomerId] ASC)
   )
  </code></pre>
  
  <p><strong>EF code:</strong></p>
  
  <pre><code>public virtual DbSet&lt;Customer&gt; Customer { get; set; }
  modelBuilder.Entity&lt;Customer&gt;(entity =&gt;
  {
      entity.Property(e =&gt; e.FirstName)
          .HasMaxLength(255)
          .IsRequired()
          .IsUnicode(false);
  
      entity.Property(e =&gt; e.LastName)
              .HasMaxLength(255)
              .IsRequired()
              .IsUnicode(false);
  
      entity.Property(e =&gt; e.AddressLine)
              .HasMaxLength(255)
              .IsRequired()
              .IsUnicode(false);
    });
  </code></pre>
  
  <p>When attempting to add data into table, code is missing columns, so it fails to insert into database. Did not know about this, and did not receive 'NOT NULL' errors, as I would see in SQL database.</p>
  
  <pre><code>var source = new Customer();
  
  source.FirstName = "Joe";  // missing Last Name and Address
  _context.Customer.Add(source);
  </code></pre>
  
  <p>So I added following code. This solves the issue, however how would I have it fail on any db error, concurrency, wrong data types etc.</p>
  
  <pre><code>try
  {
     _context.SaveChanges();
  }
  catch (DbUpdateException e)
  {
  }
  </code></pre>
  
  <p>Following were not working:
  Method 1 and 2: When these were implemented, the not null error did not show up anymore as we wanted.</p>
  
  <pre><code>try
  {
     _context.SaveChanges();
  }
  catch (Exception e)
  {
  }
  
  
  try
  {
     _context.SaveChanges();
  }
  catch
  {
  }
  </code></pre>