How do I map multiple lists with dapper

后端 未结 1 1421
一向
一向 2021-01-25 04:57

I\'ve got three classes User, Order & Project which are stored in single tables. The orders and projects both have a n:n relation with the users. To implement that I\'ve got

相关标签:
1条回答
  • 2021-01-25 05:31

    I also had trouble coming to grips with the fact that Dapper doesn't do this automatically.

    First, I'm not sure about comma-separated values for "splitOn." I thought you could only have one value there. So I have multiple columns in my result set named "ID" for example.

    Second, to get the proper 1:N relationships you need to do an extra manual step. For example, I did a 2-table join of participants and their phone numbers. Then I had to do this:

    private List<Participant> CollapseResultSet(List<Participant> rawdataset)
    {
        List<Participant> ret = new List<Participant>();
        if (!rawdataset.Any())
        {
            return ret;
        }
        else
        {
            List<string> partIds = rawdataset.Select(p => p.ID).Distinct().ToList();
            foreach (string pId in partIds)
            {
                Participant tmp = rawdataset.Where(p => p.ID == pId).FirstOrDefault();
                tmp.PhoneNumbers = rawdataset.Where(p => p.ID == pId).Select(n => n.PhoneNumbers[0]).ToList();
                ret.Add(tmp);
            }
            return ret;
        }
    }
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题