簡體   English   中英

小巧玲瓏的簡單映射

[英]Dapper simple mapping

表:

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與Customers一起獲取所有Documents 這給了我所有文件,但客戶是空的(當然):

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

編輯 - 類似但更高級的映射問題: Dapper中間映射

dapper項目頁面獲取的示例(請參閱Multi Mapping部分):

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);
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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM