Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper.NET: The varchar(4000) default

I am using Dapper.NET and when i execute the next code:

using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            con.Execute(@" insert Clients(name) values(@Name)", new {Name = "John"});
            con.Close();
        }

The query that it executes is the next one:

(@Name nvarchar(4000)) insert Clients(name) values(@Name)

And my question is: why is Dapper translating a string to a nvarchar(4000)? I mean... on the database, the name field is a nvarchar(50)...

Does anybody face this bug? How do you fix it? Have you found another bug like this?

like image 374
ascherman Avatar asked May 06 '15 23:05

ascherman


1 Answers

This is not a bug. Dapper has to pick a SQL data-type for a string parameter, without looking at the database structure (not to mention parsing your query and determining that you're inserting the parameter into a particular column).

Imagine if you were doing this:

insert Clients(name) values(@Name + 'abc')

Should Dapper have to figure out that @Name can be up to 47 characters?

You can be more specific about the size of your parameter if you like:

con.Execute(@" insert Clients(name) values(@Name)", 
    new { Name = new DbString { Value = "John", Length = 50 }});
like image 176
Blorgbeard Avatar answered Nov 06 '22 06:11

Blorgbeard