How can I force varchar length in Linq To SQL
Looking through decompiled code it doesn't really look like it pays attention to that attribute when composing the query and I don't really see a path that would let you set it
This looks to be the file that determines the parameter size to use
This part inside of InitializeParameter initializes the Size
int? determinedSize = DetermineParameterSize(sqlType, parameter); if (determinedSize.HasValue) { parameter.Size = determinedSize.Value; }
Then following the execute path is just set to 8000 for varchars and 4000 for nvarchars and doesn't really ever look at that attribute
internal virtual int? DetermineParameterSize(SqlType declaredType, DbParameter parameter) { // Output parameters and input-parameters of a fixed-size should be specifically set if value fits. bool isInputParameter = parameter.Direction == ParameterDirection.Input; if (!isInputParameter || declaredType.IsFixedSize) { if (declaredType.Size.HasValue && parameter.Size <= declaredType.Size || declaredType.IsLargeType) { return declaredType.Size.Value; } } // Preserve existing provider & server-driven behaviour for all other cases. return null; } protected int? GetLargestDeclarableSize(SqlType declaredType) { switch (declaredType.SqlDbType) { case SqlDbType.Image: case SqlDbType.Binary: case SqlDbType.VarChar: return 8000; case SqlDbType.NVarChar: return 4000; default: return null; } } internal virtual int? DetermineParameterSize(SqlType declaredType, DbParameter parameter) { // Output parameters and input-parameters of a fixed-size should be specifically set if value fits. bool isInputParameter = parameter.Direction == ParameterDirection.Input; if (!isInputParameter || declaredType.IsFixedSize) { if (declaredType.Size.HasValue && parameter.Size <= declaredType.Size || declaredType.IsLargeType) { return declaredType.Size.Value; } } // Preserve existing provider & server-driven behaviour for all other cases. return null;}
this statement
if (!isInputParameter || declaredType.IsFixedSize)
IsFixedSize returns false for varchar and nvarchar which you can see here
internal override bool IsFixedSize { get { switch (this.sqlDbType) { case SqlDbType.NText: case SqlDbType.Text: case SqlDbType.NVarChar: case SqlDbType.VarChar: case SqlDbType.Image: case SqlDbType.VarBinary: case SqlDbType.Xml: return false; default: return true; } }}
I source stepped through the code while executing a function as well to watch its execution path... It also doesn't seem like there are any useful hooks to modify before executing.. The SqlProvider has nothing useful to override or hook into either....