简体   繁体   中英

Can I Use Query Method in Dapper To Insert And Update Rows?

I'm trying to find out whether it is possible to use Query method in Dapper to insert and update rows since I want to return an object after applying insert and update actions.

I could not find any remarkable answers for that so I just tried that:

public async Task<Hotel> CreateHotel(Hotel hotel)
    {
        var sql = "INSERT INTO Hotels" +
                    " (name, city)" +
                    " VALUES (@name, @city)";

        var newHotel = new Hotel()
        {
            Name = hotel.Name,
            City = hotel.City
        };

        using (var connection = new SqlConnection(CONNECTION_STRING))
        {
            return (Hotel)await connection.QueryAsync<Hotel>(sql, newHotel);
        }
    }

But that gives that error: System.InvalidCastException: Unable to cast object of type 'System.Linq.EmptyPartition 1[HotelFinder.Entities.Hotel]' to type 'System.Collections.Generic.List 1[HotelFinder.Entities.Hotel]'.

Do you know how I can fix this or is that completely wrong?

First, you need to use the OUTPUT clause in order to return rows from an insert statement.

Second, QueryAsync will return an IEnumerable<Hotel> and not a Hotel , so you won't be able to cast it.

Put together, it would look like this

public async Task<Hotel> CreateHotel(Hotel hotel)
{
    var sql = "INSERT INTO Hotels" +
                " (name, city)" +
                " OUTPUT inserted.name, inserted.city" +
                " VALUES (@name, @city)";

    var newHotel = new Hotel()
    {
        Name = hotel.Name,
        City = hotel.City
    };

    using (var connection = new SqlConnection(CONNECTION_STRING))
    {
        return (await connection.QueryAsync<Hotel>(sql, newHotel)).SingleOrDefault();
    }
}

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