2013-04-26 59 views
0

Dapper能夠將此查詢映射到car對象。它知道汽車中的哪個屬性轉到查詢中的哪個變量。在更新查詢中映射兩個對象

Car car = new Car(); 
conn.Execute(
     "UPDATE CAR" + 
     " SET [email protected],[email protected]" + 
     " WHERE [email protected]", car; 

但我可以添加另一個變量的查詢嗎? E.g:

int c = 1000; 
conn.Execute(
     "UPDATE CAR" + 
     " SET [email protected],[email protected],[email protected]" + 
     " WHERE [email protected]", car, new { cost = c }; 

我想做到這一點,而無需在車上對象每個屬性匹配查詢的變量。這裏是示例類,但是我的真實課程中有更多的屬性。

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

回答

1

我通常只是建立一個無參數的新動態。例如:

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

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

這樣您就可以從多個對象/變量中組合動態。