title: EntityFramework Code First nullable foreign key
body: <p>I all,</p>
  
  <p>I am trying to get a nullable foreign key but can not get this to work for me.
  My model looks like this:</p>
  
  <pre><code>public class User : IdentityUser
  {
      public string Telephone { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public DateTime LastLoginDate { get; set; }
  
      public DateTime DateCreated { get; set; }
      public DateTime DateModified { get; set; }
      public string CreatedById { get; set; }
      public string ModifiedById { get; set; }
      public User CreatedBy { get; set; }
      public User ModifiedBy { get; set; }
      public bool Deleted { get; set; }
  
      public int CompanyId { get; set; }
  
      /// &lt;summary&gt;
      /// Generate the user identity
      /// &lt;/summary&gt;
      /// &lt;param name="service"&gt;The user service&lt;/param&gt;
      /// &lt;param name="authenticationType"&gt;The autentication type&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public async Task&lt;ClaimsIdentity&gt; GenerateUserIdentityAsync(UserService service, string authenticationType)
      {
  
          // Create our identity
          var userIdentity = await service.CreateIdentityAsync(this, authenticationType);
  
          // Return our identity
          return userIdentity;
      }
  }
  </code></pre>
  
  <p>The <strong>CompanyId</strong> is the foreign key that should be null, so in my <strong>DbContext</strong> I have set this mapping:</p>
  
  <pre><code>modelBuilder.Entity&lt;Company&gt;().HasMany(m =&gt; m.Members).WithOptional().HasForeignKey(m =&gt; m.CompanyId);
  </code></pre>
  
  <p>But when I run my application I always get an error:</p>
  
  <blockquote>
    <ul>
    <li>InnerException  {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Users_dbo.Companies_CompanyId\". The conflict occurred in database \"melanite\", table \"dbo.Companies\", column 'Id'.\r\nThe statement has been terminated."}   System.Exception {System.Data.SqlClient.SqlException}</li>
    </ul>
  </blockquote>
  
  <p>does anyone know how I can change my mapping to work correctly?</p>