DbString, IsFixedLength and IsAnsi for varchar

被刻印的时光 ゝ 提交于 2020-08-17 05:30:06

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/47741126/dbstring-isfixedlength-and-isansi-for-varchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!