Dapper能够将此查询映射到car
对象。它知道汽车中的哪个属性转到查询中的哪个变量。
Car car = new Car();
conn.Execute(
"UPDATE CAR" +
" SET COLOR=@Color,MODEL=@Model" +
" WHERE ID=@Id", car;
但是我可以在查询中添加另一个变量吗? E.g:
int c = 1000;
conn.Execute(
"UPDATE CAR" +
" SET COLOR=@Color,MODEL=@Model,COST=@cost" +
" WHERE ID=@Id", car, new { cost = c };
我想这样做而不必将car对象中的每个属性与查询中的变量相匹配。这是示例类,但我在真正的类中有更多属性。
public class Car {
public int Id { get; set; }
public string Color { get; set; }
public string Model { get; set; }
}
答案 0 :(得分:1)
我通常只是为所有参数创建一个新的动态。例如:
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});
这样您就可以从多个对象/变量中组合动态。
答案 1 :(得分:0)
可能有一个更好的答案,但现在有效:
int c = 1000;
conn.Execute(
"UPDATE CAR" +
" SET COLOR=@Color,MODEL=@Model,COST=" + c +
" WHERE ID=@Id", car;