Map two objects in an update query

dapper

Question

Dapper is able to map this query to the car object. It knows which property in the car goes to which variable in the query.

Car car = new Car();
conn.Execute(
      "UPDATE CAR" +
      " SET COLOR=@Color,MODEL=@Model" +
      " WHERE ID=@Id", car;

But can I add another variable to the query? E.g:

int c = 1000; 
conn.Execute(
      "UPDATE CAR" +
      " SET COLOR=@Color,MODEL=@Model,COST=@cost" +
      " WHERE ID=@Id", car, new { cost = c };

I'd like to do this without having to match every property in the car object to a variable in the query. Here's the example class, but I have a lot more properties in my real class.

public class Car {
    public int Id { get; set; }
    public string Color { get; set; }
    public string Model { get; set; }
}

Accepted Answer

There might be a better answer but this worked for now:

int c = 1000; 
conn.Execute(
      "UPDATE CAR" +
      " SET COLOR=@Color,MODEL=@Model,COST=" + c +
      " WHERE ID=@Id", car;

Popular Answer

I usually just create a new dynamic for all parameters. For example:

var car = new Car();
car.Color = "Black";
car.Model = "BMW";
car.Id = 123;
var cost = 53000

DbConnection.Execute(@"update car set color=@color, model = @model, cost = @cost where id = @id",
                new { color = car.Color, model = car.Model, cost = cost, id=car.Id});

This way you can assemble the dynamic from multiple objects/variables.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why