Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbString, IsFixedLength and IsAnsi for varchar

Tags:

dapper

I am new to Dapper, want to know why below is suggested, when my code runs without it?

Ansi Strings and varchar

Dapper supports varchar params, if you are executing a where clause on a varchar column using a param be sure to pass it in this way:

 Query<Thing>("select * from Thing where Name = @Name", new {Name = new
 DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi
 = true });

On SQL Server it is crucial to use the unicode when querying unicode and ansi when querying non unicode.

Below is my code, which runs against SQL server 2012 without using DbString etc.

create table Author (
 Id int identity(1,1),
 FirstName varchar(50),
 LastName varchar(50)
);
go
insert into Author (FirstName, LastName) values ('Tom', 'John');

        public Author FindByVarchar(string firstName)
        {
            using (IDbConnection db = DBHelper.NewSqlConnection())
            {
                return db.Query<Author>("Select * From Author WHERE FirstName = @firstName", new { firstName }).SingleOrDefault();
            }
        }

Questions:

1 Why is DbString type used in this case?

2 Why the length is set to 10 (e.g.Length = 10) when "abcde" is 5?

3 Do I still need to use DbString when my current code works?

4 Is it correct to set IsAnsi = false for unicode column?

5 For varchar column, is it correct to set IsFixedLength = false, and ignore setting Length?

like image 504
Pingpong Avatar asked Dec 10 '17 16:12

Pingpong


1 Answers

The purpose of the example is that it is describing a scenario where the data type is char(10). If we just used "abcde", Dapper might think that nvarchar(5) was appropriate. This would be very inefficient in some cases - especially in a where clause, since the RDBMS can decide that it can't use the index, and instead needs to table scan doing a string conversion for every row in the table from char(10) to the nvarchar version. It is for this reason that DbString exists - to help you control exactly how Dapper configures the parameter for text data.

I think this answers your 1 and 2.

3: are you using ANSI (non-unicode text) or fixed-width text? Note that the ANSI default can also be set globally if you always avoid unicode

4: yes

5: yes

4+5 combined: if you're using nvarchar: just use string

like image 114
Marc Gravell Avatar answered Oct 03 '22 00:10

Marc Gravell