使用 Dapper 进行多映射查询
本文关键字:映射 查询 Dapper 使用 | 更新日期: 2023-09-27 18:36:34
我的数据库中有这些类及其等效表:
public class Entity
{
public int Id { get; set; }
public List<EntityIdentifier> Identifiers { get; set; }
public BaseEntity()
{
Identifiers = new List<EntityIdentifier>();
}
}
public class EntityIdentifier
{
public int Id { get; set; }
public int EntityId { get; set; }
public string Code { get; set; }
public string Value { get; set; }
}
我想使用 Dapper 查询数据库并自动映射数据。
我有这个多映射的例子,来自 Dapper git 页面:
var sql =
@"select * from #Posts p
left join #Users u on u.Id = p.OwnerId
Order by p.Id";
var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();
post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);
但是,在此示例中,每个子项(帖子)都有一个指向其父项(用户)的链接。就我而言,是父项(实体)指向子项(标识符)列表。
我需要如何根据我的情况调整代码?
这是我正在使用的 SQL 查询:
SELECT e.*, i.*
FROM Entity e INNER JOIN EntityIdentifier i ON i.EntityId = e.Id
这是我
在Dapper相关网站上找到的一个例子。这里的重点是有一个字典,您可以在其中将 Entity.ID 保留为键,将实体保留为字典值。然后在lambda表达式中检查字典是否已经包含实体,如果是,只需将实体标识符添加到实体列表中,否则将Dapper返回的实体添加到字典中
string cmdText = @"SELECT e.*, i.*
FROM Entity e INNER JOIN Identifier i ON i.EntityId = e.Id";
var lookup = new Dictionary<int, Entity>();
using (IDbConnection connection = OpenConnection())
{
var multi = connection.Query<Entity, EntityIdentifier, Entity>(cmdText,
(entity, identifier) =>
{
Entity current;
if (!lookup.TryGetValue(entity.ID, out current))
{
lookup.Add(entity.ID, current = entity);
current.Identifiers = new List<EntityIdentifier>();
}
current.Identifiers.Add(identifier);
return current;
}, splitOn: "i.ID").Distinct();
return multi;
}
有时,这因参数splitOn而变得复杂。不确定您是否需要重复它,将其显式添加到 Select 语句中(我通常使用 IDTable 模式)