Use dapper encountered problems and solutions

One problem encountered when using data query dapper today be the problem recurs make a record, so later forget and make the same mistake.

They have to realize is: select * from tablename where id in (1,2) such a query. Own that the wording should be like this, as follows:

List<CICUser> userList = new List<CICUser>();
            using (IDbConnection conn = new SqlConnection(sqlConnectionString))
            {
                int[] idarr = new int[] { 1, 2, 3 };
                string sqlCommandText = @"SELECT * FROM CICUser s WHERE s.UserId IN (@UserId) ";
                
                userList = conn.Query<CICUser>(sqlCommandText, new { UserId = idarr },null,true,null, CommandType.Text).ToList();
                

            }

After being given the run, as follows:

 

 The problem is to find a cause that is not wrong to write their own, that in the end is where the problem is Na, do not want to study the source code, then look to see Zage get the sql statement generated than under the sql statement to see where there are problems .

Then you based on the database tool to track get sql statement, as follows:

 

exec sp_executesql N'SELECT * FROM CICUser s WHERE s.UserId IN ((@UserId1,@UserId2,@UserId3)) ',N'@UserId1 int,@UserId2 int,@UserId3 int',@UserId1=1,@UserId2=2,@UserId3=3

After executing the sql statement newspaper "", "Incorrect syntax near." It seems that generated sql statement is a problem, go into the generated sql statement would be much easier.

The original generated sql statement here than a pair of brackets , is the cause.

To find the code inside the brackets where they come from, try to own the code to remove the brackets depending on the position of the brackets, modify your code as follows:

 List<CICUser> userList = new List<CICUser>();
            using (IDbConnection conn = new SqlConnection(sqlConnectionString))
            {
                int[] idarr = new int[] { 1, 2, 3 };
                string sqlCommandText = @"SELECT * FROM CICUser s WHERE s.UserId IN @UserId ";
                
                userList = conn.Query<CICUser>(sqlCommandText, new { UserId = idarr },null,true,null, CommandType.Text).ToList();
                

            }

Go running, successful track get sql statement:

exec sp_executesql N'SELECT * FROM CICUser s WHERE s.UserId IN (@UserId1,@UserId2,@UserId3) ',N'@UserId1 int,@UserId2 int,@UserId3 int',@UserId1=1,@UserId2=2,@UserId3=3

This is normal, and many parentheses gone.

In doing so original query, parameters do not need parentheses, dapper we will automatically add parentheses.

 

@UserId

Guess you like

Origin www.cnblogs.com/fgq520328/p/11876462.html