简体   繁体   中英

Using Entity Framework to save a string value to a SQL table which contains a Null character, cuts of all proceeding characters

I need to save the null character "\\0" along with others to a nvarchar column in my SQL database. However when doing so it will ignore all character after the first "\\0" , so if this is at the start of the string an empty string value will be saved to the database.

This example below will save an empty string to the Text column which is a nvarchar column.

TestEntities te = new TestEntities();

te.Table_1.Add(new Table_1 { Text = "\0tes\0 ttest \0" });
te.SaveChanges();

Where as this example will save the text tes .

TestEntities te = new TestEntities();

te.Table_1.Add(new Table_1 { Text = "tes\0test" });
te.SaveChanges();

Is there an explanation for this behavior and any way I can get around this?

EDIT: after reading the answers, as SQL terminates the string after a "\\0" character I am converting my string into a Base64 string. Example below.

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);
}

This produces the output dABlAHMAAAAgAHQAdABlAHMAdAAgAAAA from my original value tes\\0 ttest \\0

I'm afraid SQL will consider \\0 as the end of the string. Try storing the data as var binary and using:

System.Text.Encoding.UTF8.GetBytes("\\0tes\\0 ttest \\0") to write and

System.Text.Encoding.UTF8.GetString(table.Text) to read.

I'm not sure why this is happening, perhaps EF uses \\0 as a string terminator.

To overcome the problem, if nvarchar is the only option for you, you could encode the data before inserting and decode after retrieving, base 64 should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM