用于 varchar 的 DbString、IsFixedLength 和 IsAnsi
DbString, IsFixedLength and IsAnsi for varchar
我是 Dapper 的新手,想知道为什么在我的代码没有它运行时会出现以下建议?
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.
下面是我的代码,它在 SQL 服务器 2012 上运行,没有使用 DbString 等
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();
}
}
问题:
1 为什么在这种情况下使用 DbString 类型?
2 为什么当“abcde”为5时长度设置为10(e.g.Length = 10)?
3 当我当前的代码可以工作时,我还需要使用 DbString 吗?
4 为 unicode 列设置 IsAnsi = false 是否正确?
5 对于 varchar 列,设置 IsFixedLength = false 并忽略设置 Length 是否正确?
该示例的目的是描述数据类型为 char(10)
的场景。如果我们只使用 "abcde"
,Dapper 可能会认为 nvarchar(5)
是合适的。在某些情况下这会非常低效——尤其是在 where
子句中,因为 RDBMS 可以决定它不能使用索引,而是需要 table 扫描对每一行进行字符串转换在 table 从 char(10)
到 nvarchar
的版本中。正是出于这个原因,DbString
存在 - 帮助您准确地 控制 Dapper 如何配置文本数据的参数。
我认为这回答了您的第 1 和第 2 个问题。
3:您使用的是 ANSI(非 unicode 文本)还是等宽文本?请注意,如果您 always 避免使用 unicode
,也可以全局设置 ANSI 默认值
4:是
5:是
4+5 组合:如果您使用 nvarchar
:只需使用 string
我是 Dapper 的新手,想知道为什么在我的代码没有它运行时会出现以下建议?
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.
下面是我的代码,它在 SQL 服务器 2012 上运行,没有使用 DbString 等
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();
}
}
问题:
1 为什么在这种情况下使用 DbString 类型?
2 为什么当“abcde”为5时长度设置为10(e.g.Length = 10)?
3 当我当前的代码可以工作时,我还需要使用 DbString 吗?
4 为 unicode 列设置 IsAnsi = false 是否正确?
5 对于 varchar 列,设置 IsFixedLength = false 并忽略设置 Length 是否正确?
该示例的目的是描述数据类型为 char(10)
的场景。如果我们只使用 "abcde"
,Dapper 可能会认为 nvarchar(5)
是合适的。在某些情况下这会非常低效——尤其是在 where
子句中,因为 RDBMS 可以决定它不能使用索引,而是需要 table 扫描对每一行进行字符串转换在 table 从 char(10)
到 nvarchar
的版本中。正是出于这个原因,DbString
存在 - 帮助您准确地 控制 Dapper 如何配置文本数据的参数。
我认为这回答了您的第 1 和第 2 个问题。
3:您使用的是 ANSI(非 unicode 文本)还是等宽文本?请注意,如果您 always 避免使用 unicode
,也可以全局设置 ANSI 默认值4:是
5:是
4+5 组合:如果您使用 nvarchar
:只需使用 string