title: Using Entity Framework to save a string value to a SQL table which contains a Null character, cuts of all proceeding characters
body: <p>I need to save the null character <code>"\0"</code> along with others to a <code>nvarchar</code> column in my SQL database. However when doing so it will ignore all character after the first <code>"\0"</code>, so if this is at the start of the string an empty string value will be saved to the database. </p>
  
  <p>This example below will save an empty string to the <code>Text</code> column which is a <code>nvarchar</code> column.</p>
  
  <pre><code>TestEntities te = new TestEntities();
  
  te.Table_1.Add(new Table_1 { Text = "\0tes\0 ttest \0" });
  te.SaveChanges();
  </code></pre>
  
  <p>Where as this example will save the text <code>tes</code>.</p>
  
  <pre><code>TestEntities te = new TestEntities();
  
  te.Table_1.Add(new Table_1 { Text = "tes\0test" });
  te.SaveChanges();
  </code></pre>
  
  <p>Is there an explanation for this behavior and any way I can get around this?</p>
  
  <p><strong>EDIT:</strong> after reading the answers, as SQL terminates the string after a <code>"\0"</code> character I am converting my string into a Base64 string. Example below. </p>
  
  <pre><code>static void Main(string[] args)
  {
      TestEntities te = new TestEntities();
  
      string value = "tes\0 ttest \0";
      Table_1 table = new Table_1 { Text = Base64Encode(value) };
      te.Table_1.Add(table);
      te.SaveChanges();
  
      string text = Base64Decode(table.Text);
  }
  
  public static string Base64Encode(string plainText)
  {
      byte[] bytes = new byte[plainText.Length * sizeof(char)];
      System.Buffer.BlockCopy(plainText.ToCharArray(), 0, bytes, 0, bytes.Length);
  
      return System.Convert.ToBase64String(bytes);
  }
  
  public static string Base64Decode(string base64EncodedData)
  {
      var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  
      char[] chars = new char[base64EncodedBytes.Length / sizeof(char)];
      System.Buffer.BlockCopy(base64EncodedBytes, 0, chars, 0, base64EncodedBytes.Length);
  
      return new string(chars);
  }
  </code></pre>
  
  <p>This produces the output <code>dABlAHMAAAAgAHQAdABlAHMAdAAgAAAA</code> from my original value <code>tes\0 ttest \0</code></p>