Linq中有很多人使用Dapper

时间:2018-06-10 17:53:25

标签: c# linq dapper

我有地方,每个地方都可以有很多标签。每个标签都可以分配到很多地方。

public class Place {
    public int Id { get; set; }
    public string PlaceName { get; set; }

    public IEnumerable<Tag> Tags { get; set; }
}

public class Tag {
    public int Id { get; set; }
    public string TagName { get; set; }
}

public class TagPlace {
    public int Id { get; set; }
    public PlaceId { get; set; }
    public TagId { get; set; }
}

数据库具有适当的外键等效表。

我想获得一系列地方,我希望每个地方都有一个合适的标签集合。我猜可能需要使用Linq。

我已经找到了相关的各种文章,但它们并不完全相同/处理一个整数列表而不是两个对象集合。

例如 https://social.msdn.microsoft.com/Forums/en-US/fda19d75-b2ac-4fb1-801b-4402d4bd5255/how-to-do-in-linq-quotselect-from-employee-where-id-in-101112quot?forum=linqprojectgeneral

LINQ Where in collection clause

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

使用Dapper的经典方法是使用Dictionary来存储主要对象,而查询枚举记录

public  IEnumerable<Place> SelectPlaces()
{
    string query = @"SELECT p.id, p.PlaceName, t.id, t.tagname
                     FROM Place p INNER JOIN TagPlace tp ON tp.PlaceId = p.Id
                     INNER JOIN Tag t ON tp.TagId = t.Id";
    var result = default(IEnumerable<Place>);
    Dictionary<int, Place> lookup = new Dictionary<int, Place>();
    using (IDbConnection connection = GetOpenedConnection())
    {
         // Each record is passed to the delegate where p is an instance of
         // Place and t is an instance of Tag, delegate should return the Place instance.
         result = connection.Query<Place, Tag, Place(query, (p, t) =>
         {
              // Check if we have already stored the Place in the dictionary
              if (!lookup.TryGetValue(p.Id, out Place placeFound))
              {
                   // The dictionary doesnt have that Place 
                   // Add it to the dictionary and 
                   // set the variable where we will add the Tag
                   lookup.Add(p.Id, p);
                   placeFound = p;
                   // Probably it is better to initialize the IEnumerable
                   // directly in the class 
                   placeFound.Tags = new List<Tag>();
              }

              // Add the tag to the current Place.
              placeFound.Tags.Add(t);
              return placeFound;

          }, splitOn: "id");
          // SplitOn is where we tell Dapper how to split the record returned
          // in the two instances required, but here SplitOn 
          // is not really needed because "Id" is the default.

     }
     return result;
}