简单的内连接结果与Dapper?

Per*_*eck 33 dapper

我似乎无法找到我的问题的文档或示例(现在已经搜索了一段时间).我认为我的问题很简单,所以这里就是这样.

我有两张桌子.我的主表名为Persons,辅助表名为PersonEntries.对于Person表中的每个人,我可以在PersonEntries表中有0个或更多个条目.像这样.

Table: Person
Id
Name

Table: PersonEntry
PersonId
CheckinTime
CheckoutTime
Run Code Online (Sandbox Code Playgroud)

我有两个像这样的对象

public class Person {
  public string Name;
  public List<PersonEntry> PersonEntries;
}

public class PersonEntry {
  public DateTime CheckinTime;
  public DateTime CheckoutTime;
}
Run Code Online (Sandbox Code Playgroud)

如果我是从数据库中获取它到我的c#类中我该怎么做?我可以将一个表映射到我的c#类中,并为每个表执行此操作,但随后我将匹配哪些条目映射到哪个人.

我已经看过几个将一个PersonEntry映射到一个Person的例子,这里的问题是我有一个从零到多的关系.我的人有一个PersonEntry项目列表.

Jer*_*n K 37

你可以做这样的事情(参见https://www.tritac.com/blog/dappernet-by-example):

public class Shop {
  public int? Id {get;set;}
  public string Name {get;set;}
  public string Url {get;set;}
  public IList<Account> Accounts {get;set;}
}

public class Account {
  public int? Id {get;set;}
  public string Name {get;set;}
  public string Address {get;set;}
  public string Country {get;set;}
  public int ShopId {get;set;}
}

var lookup = new Dictionary<int, Shop>()
conn.Query<Shop, Account, Shop>(@"
                SELECT s.*, a.*
                FROM Shop s
                INNER JOIN Account a ON s.ShopId = a.ShopId                    
                ", (s, a) => {
                     Shop shop;
                     if (!lookup.TryGetValue(s.Id, out shop)) {
                         lookup.Add(s.Id, shop = s);
                     }
                     if (shop.Accounts == null) 
                         shop.Accounts = new List<Account>();
                     shop.Accounts.Add(a);
                     return shop;
                 }
                 ).AsQueryable();
var resultList = lookup.Values;
Run Code Online (Sandbox Code Playgroud)