使用Dapper如何得到简单的内连接结果?

43

我似乎找不到我的问题的文档或例子(已经搜索了一段时间)。 我认为我的问题非常简单,所以来吧。

我有两个表。 我的主要表名为Persons,第二个表名为PersonEntries。 对于Person表中的每个人,在PersonEntries表中都可以有0个或多个条目。像这样。

Table: Person
Id
Name

Table: PersonEntry
PersonId
CheckinTime
CheckoutTime

我有两个像这样的对象

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

public class PersonEntry {
  public DateTime CheckinTime;
  public DateTime CheckoutTime;
}
如果我要将它从数据库中获取到我的 C# 类中,我该怎么做呢?我可以将单个表映射到我的 C# 类中,并为每个表执行此操作,但这样我就必须将条目与人员匹配起来。
我已经看到了将一个 PersonEntry 映射到一个 Person 的多个示例,问题在于我有零对多的关系。我的 Person 有一个 PersonEntry 项的列表
1个回答

52

你可以像这样做(参见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;

1
最后一个参数打开了强大的功能。我没有想到可以这样解决 - 希望有更类似本地的功能,但这也可以。谢谢 :) - Per Hornshøj-Schierbeck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接