小巧玲珑的简单映射

时间:2012-04-16 08:30:37

标签: c# sql-server orm dapper

表:

create table Documents 
   (Id int, 
    SomeText varchar(100), 
    CustomerId int, 
    CustomerName varchar(100)
   )

insert into Documents (Id, SomeText, CustomerId, CustomerName) 
   select 1, '1', 1, 'Name1' 
     union all
   select 2, '2', 2, 'Name2'

类:

public class Document
{
    public int Id { get; set; }
    public string SomeText { get; set; }
    public Customer { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

如何使用Dapper Documents获取所有Customers?这给了我所有文件,但客户是空的(当然):

connection.Query<Document>("select Id, SomeText, CustomerId, CustomerName from Documents")...

编辑 - 类似但更高级的映射问题:Dapper intermediate mapping

2 个答案:

答案 0 :(得分:6)

取自dapper project page的示例(请参阅多重映射部分):

var sql = 
@"select * from #Posts p 
left join #Users u on u.Id = p.OwnerId 
Order by p.Id";

var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();

post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);

答案 1 :(得分:4)

var docs = connection.Query<Document, Customer, Document>(
    "select Id, SomeText, CustomerId as [Id], CustomerName as [Name] from Documents",
    (doc, cust) => { doc.Customer = cust; return doc; }).ToList();