简体   繁体   中英

Query using Dapper in C# & MySQL

I'm new to C# and I'm making a small software to practice.

I've built a query to get the last Dispatch_ID number(which is not Auto-increment). The code i'm using goes something like this:

public string GetLastDispatchNum()
    {
        using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal("FineCreteDB")))
        {
            var output=connection.Query("SELECT `Dispatch_ID` FROM `DispatchData` ORDER BY `Dispatch_ID` DESC LIMIT 1").Select(x=>x.Dispatch_ID).ElementAt(0);
            return output;
        }
    }

Although this does get my job done, I feel I'm not using dapper properly here, and this can be much neater. The query "SELECT Dispatch_ID FROM DispatchData ORDER BY Dispatch_ID DESC LIMIT 1" itself returns just one value & one column. Therefore using.Select(x=>x.Dispatch_ID) &.ElementAt(0) seems a bit repetitive.

Is there a better way to go about this?

I don't know if it adds much compared to the other answers, but I prefer QuerySingle in cases where I expect a single value. It throws an exception if there isn't exactly one item in the result set.

public int GetLastDispatchNum()
{
    using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.CnnVal("FineCreteDB")))
    {
        int output=connection.QuerySingle<int>("SELECT `Dispatch_ID` FROM `DispatchData` ORDER BY `Dispatch_ID` DESC LIMIT 1").Select(x=>x.Dispatch_ID).ElementAt(0);
        return output;
    }
}

It ensures two things:

  • A default value (maybe null) won't cause problems at a later stage.
  • An inconsistency in my database or my database model won't go unnoticed.

Personally, I would use this instead:

var output=connection.Query<int>("SELECT `Dispatch_ID` FROM `DispatchData` ORDER BY `Dispatch_ID` DESC LIMIT 1").FirstOrDefault();

Can't say it is technically any better/faster, but seems cleaner to me.

To update the Dapper query so you don't have to use.ElementAt(0), you can simply write out the Dapper code like:

// Assuming that Dispatch_ID is an int
var output = connection.QueryFirst<int>("SELECT `Dispatch_ID` FROM `DispatchData` ORDER BY `Dispatch_ID` DESC LIMIT 1");

Also if you want to use the generic in Dapper functions I would recommend that you use something that matches what you are retrieving, hence why I changed it from <DispatchData> to <int> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM