问题
I have a very annoying problem with LINQ and MS SQL Server.
Im currently making some software in WPF C# and use LINQ to generate classes from the data in the database.
However, when i update a nvarchar or varchar field in the DB from my program, LINQ adds trailing spaces to the string!
I have a field in a table defined like this:
ProductName = NVARCHAR(10)
So if i do this:
Product.Name = "Bike";
Product.Name = Product.Name.Trim();
repository.Add(Product); // Runs an .InsertOnSubmit
repository.Save(); // Runs a .SubmitChanges
then the resulting data in the DB is "Bike[SPACE][SPACE][SPACE][SPACE][SPACE][SPACE]" where [SPACE] is just a space (can't write multiple spaces in this text here).
Why does it do this, and how do i make it stop adding those annoying trailing spaces?
Thanks in advance
回答1:
If i remember correctly i had the same problem...It's not because of linq but because of column type. Please try to change it to VARCHAR.
回答2:
The auto-generated LINQ classes defined the NVarchar fields in the following way:
[Column(Storage="_Text", DbType="NChar(20) NOT NULL", CanBeNull=false)]
public string Text
{
get
{
return this._Text;
}
set
{
if ((this._Text != value))
{
this.OnTextChanging(value);
this.SendPropertyChanging();
this._Text = value;
this.SendPropertyChanged("Text");
this.OnTextChanged();
}
}
}
Where the Column settings should be:
[Column(Storage="_Text", DbType="NVarChar(20) NOT NULL", CanBeNull=false)]
The problem occurred because i updated the type in the SQL database without re-generating the LINQ classes.
回答3:
also Nchar makes same thing.
These types fills blanks : Nchar and Nvarchar
I Have converted my db and updated my model. All fixed.
check that...
What is the difference between char, nchar, varchar, and nvarchar in SQL Server?
If you dont want to change your model you can use mssql trim function.
来源:https://stackoverflow.com/questions/1879422/linq-puts-unwanted-trailing-spaces-on-strings