【问题标题】:Simple inner join result with Dapper?Dapper 的简单内部连接结果?
【发布时间】:2013-12-10 10:33:58
【问题描述】:

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

我有两张桌子。我的主表称为 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# 类中并为每个表执行此操作,但随后我将匹配哪些条目映射到哪些人。

我见过几个将 ONE PersonEntry 映射到 ONE Person 的例子,这里的问题是我有一个零对多的关系。我的 Person 有一个 PersonEntry 项的LIST

【问题讨论】:

    标签: dapper


    【解决方案1】:

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

    【讨论】:

    • 最后一个参数打开 op 以获得强大的功能。我没想过那样解决它 - 希望有一个更像原生的功能,但这会做。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多