Dapper ORM嵌套对象

时间:2012-06-05 23:59:09

标签: orm dapper

我有一个客户说我使用了Dapper ORM,这是我以前从未使用过的。我有嵌套对象的问题。我有一个主类(Location),它有一个嵌入式值对象类(Address)。这两个类看起来像这样:

class Location {
    int Id;
    string LocationName;
    Address LocationAddress;
}

Class Address {
    string Street;
    string City;
    string State;
    string ZipCode;
}

SQL:

SELECT Id, LocationName, Street, City, State, ZipCode FROM Locations

我看了很多例子,但我无法正确设置查询。我只是不了解Dapper足以使结构正确。

1 个答案:

答案 0 :(得分:10)

您可以在dapper查询中使用“splitOn”参数。

var sql = "SELECT Id, LocationName, Street, City, State, ZipCode FROM Locations";
var conn = // your get connection logic here. 

using(conn)
{
 conn.Open();
 var locations = conn.Query<Location,Address,Location>(sql, (location, address) => 
                 {
                   location.LocationAddress = address;
                   return location;
                 }, splitOn: "Street");
}

如果记录集中的对象未被名为“Id”的列“拆分”,则需要使用SplitOn。