Dapper official translation Tutorial 4: QueryFirst Dapper method of
QueryFirst method described
QueryFirst method is an extension method, it can be called IDbConnection object, you can execute a query, and mapped to the result.
You can be mapped type:
The method may be used parameter QueryFirst
parameter name | Parameter Description |
sql | Database statement |
param | Query parameters |
transaction | Services used |
commandTimeout | Execution timeout |
commandType | Statement Types |
First,FirstOrDefault,Single,SingleOrDefault对比
Result | No Item | One Item | Many Items |
---|---|---|---|
First | Exception | Item | First Item |
Single | Exception | Item | Exception |
FirstOrDefault | Default | Item | First Item |
SingleOrDefault | Default | Item | Exception |
The difference between xx and xxOrDefault: xx at the time could not find the data throws an exception, but xxOrDefault will return to the default value, so when there is no uncertainty values, priority use xxOrDefault.
When containing a plurality of values, and Single SingleOrDefault will raise an exception, or FirstOrDefault First and returns a value that satisfies the first condition.
In summary, priority use FirstOrDefault
Anonymous queries
-
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
-
-
using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
-
{
-
var orderDetail = connection.QueryFirst(sql, new {OrderDetailID = 1});
-
-
FiddleHelper.WriteTable(orderDetail);
-
}
Strongly typed queries
-
string sql = "SELECT * FROM OrderDetails WHERE OrderDetailID = @OrderDetailID;";
-
-
using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
-
{
-
var orderDetail = connection.QueryFirst(sql, new {OrderDetailID = 1});
-
-
FiddleHelper.WriteTable(orderDetail);
-
}