LINQ puts unwanted trailing spaces on strings
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 th开发者_如何学Goe 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
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.
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.
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.
精彩评论