Simple inner join result with Dapper?

半腔热情 提交于 2019-12-17 17:54:29

问题


I can't seem to find documentation or examples for my problem (been searching a while now). I think my problem is pretty straightforward, so here goes.

I have two tables. My primary table is called Persons and the secondary table is PersonEntries. For each person in Person table, i can have 0 or more entries in the PersonEntries table. Like this.

Table: Person
Id
Name

Table: PersonEntry
PersonId
CheckinTime
CheckoutTime

I have two objects like this

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

public class PersonEntry {
  public DateTime CheckinTime;
  public DateTime CheckoutTime;
}

If i was to get it from the database into my c# classes how would i do it? I can map a single table into my c# class and do it for each table, but then i'm left to match what entries maps to what person.

I've seen several examples of mapping ONE PersonEntry to ONE Person, the problem here is that i have a zero-to-many relation. My Person have a LIST of PersonEntry items.


回答1:


You can do something like this (see 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;


来源:https://stackoverflow.com/questions/20492071/simple-inner-join-result-with-dapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!