String or binary data would be truncated.The statement has been terminated

ef-code-first entity-framework

Question

I am updating my database using the update-database command in Entity Framework and it is raising an error with the message: String or binary data would be truncated. The statement has been terminated

How can I allow the update to work?

1
6
11/27/2018 9:32:35 AM

Popular Answer

Take this code first entity:

public class Something
{
    public string SomeProperty { get; set; }
}

That will create a column of type NVARCHAR(MAX) which will let you pretty much store any size text.

Now we apply an annotation like this:

public class Something
{
    [MaxLength(50)]
    public string SomeProperty { get; set; }
}

So now the migration from this has to shorten your column to 50 characters only. If you have entries that are longer that 50 characters, you will get that error message.

Solution 1

Fix the data! Remove any data longer than 50 characters. Using SQL, either delete the offending rows:

DELETE FROM MyTable
WHERE LEN(MyColumn) > 50

Or, probably a better idea is to manually truncate the data:

UPDATE MyTable
SET MyColumn = LEFT(MyColumn, 50)
WHERE LEN(MyColumn) > 50

Solution 2 (not 100% sure this will work)

Let the migration truncate the data by using this command:

Update-Database -Force
17
7/24/2014 10:42:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow