views:

50

answers:

2

Hi

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

+2  A: 

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.

Cristian Boariu
As i wrote in my question, the database IS using NVarChar. However, i found the problem.
Kaare Mai
+1  A: 

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.

Kaare Mai