我已经编写了这段代码,用于预测一对多的关系,但它无法正常工作:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
IEnumerable<Store> stores = connection.Query<Store, IEnumerable<Employee>, Store>
(@"Select Stores.Id as StoreId, Stores.Name,
Employees.Id as EmployeeId, Employees.FirstName,
Employees.LastName, Employees.StoreId
from Store Stores
INNER JOIN Employee Employees ON Stores.Id = Employees.StoreId",
(a, s) => { a.Employees = s; return a; },
splitOn: "EmployeeId");
foreach (var store in stores)
{
Console.WriteLine(store.Name);
}
}
有人能发现错误吗?
修改
这些是我的实体:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public IList<Store> Stores { get; set; }
public Product()
{
Stores = new List<Store>();
}
}
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Product> Products { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public Store()
{
Products = new List<Product>();
Employees = new List<Employee>();
}
}
修改
我将查询更改为:
IEnumerable<Store> stores = connection.Query<Store, List<Employee>, Store>
(@"Select Stores.Id as StoreId ,Stores.Name,Employees.Id as EmployeeId,Employees.FirstName,
Employees.LastName,Employees.StoreId from Store Stores INNER JOIN Employee Employees
ON Stores.Id = Employees.StoreId",
(a, s) => { a.Employees = s; return a; }, splitOn: "EmployeeId");
我摆脱了异常!但是,员工根本没有映射。我仍然不确定在第一次查询中它与IEnumerable<Employee>
有什么问题。
答案 0 :(得分:139)
这篇文章展示了如何查询highly normalised SQL database,并将结果映射到一组高度嵌套的C#POCO对象。
成分:
让我解决此问题的洞察力是将MicroORM
与mapping the result back to the POCO Entities
分开。因此,我们使用两个独立的库:
基本上,我们使用Dapper来查询数据库,然后使用Slapper.Automapper将结果直接映射到我们的POCO中。
List<MyClass1>
又包含List<MySubClass2>
等),所以Slapper.Automapper需要处理几行代码才能处理你抛出的任何内容。 inner joins
创建扁平化查询以返回平面结果比创建多个select语句要容易得多,在客户端进行拼接。inner join
(它带回重复项)将其展平,我们应该使用多个{{ 1}}语句并在客户端将所有内容拼接在一起(参见本页的其他答案)。在我的测试中,Slapper.Automapper为Dapper返回的结果增加了一小部分开销,这意味着它仍然比实体框架快10倍,并且组合仍然非常接近理论最大值速度SQL + C#能够。
在大多数实际情况中,大部分开销都是在一个不太理想的SQL查询中,而不是在C#端对结果进行一些映射。
迭代总数:1000
select
: 1.889 毫秒,每个查询使用Dapper by itself
。3 lines of code to return the dynamic
:每个查询 2.463 毫秒,使用额外的Dapper + Slapper.Automapper
。在此示例中,我们有3 lines of code for the query + mapping from dynamic to POCO Entities
列表,每个Contacts
可以有一个或多个Contact
。
phone numbers
public class TestContact
{
public int ContactID { get; set; }
public string ContactName { get; set; }
public List<TestPhone> TestPhones { get; set; }
}
public class TestPhone
{
public int PhoneId { get; set; }
public int ContactID { get; set; } // foreign key
public string Number { get; set; }
}
TestContact
请注意,此表有一个外键TestPhone
,它引用ContactID
表(这对应于上面POCO中的TestContact
)。
在我们的SQL查询中,我们使用尽可能多的List<TestPhone>
语句来获取flat, denormalized form中所需的所有数据。是的,这可能会在输出中产生重复,但当我们使用Slapper.Automapper自动将此查询的结果直接映射到我们的POCO对象图中时,这些重复项将自动消除。
JOIN
USE [MyDatabase];
SELECT tc.[ContactID] as ContactID
,tc.[ContactName] as ContactName
,tp.[PhoneId] AS TestPhones_PhoneId
,tp.[ContactId] AS TestPhones_ContactId
,tp.[Number] AS TestPhones_Number
FROM TestContact tc
INNER JOIN TestPhone tp ON tc.ContactId = tp.ContactId
在Visual Studio中查看,我们可以看到Slapper.Automapper已正确填充了我们的POCO实体,即我们有const string sql = @"SELECT tc.[ContactID] as ContactID
,tc.[ContactName] as ContactName
,tp.[PhoneId] AS TestPhones_PhoneId
,tp.[ContactId] AS TestPhones_ContactId
,tp.[Number] AS TestPhones_Number
FROM TestContact tc
INNER JOIN TestPhone tp ON tc.ContactId = tp.ContactId";
string connectionString = // -- Insert SQL connection string here.
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
// Can set default database here with conn.ChangeDatabase(...)
{
// Step 1: Use Dapper to return the flat result as a Dynamic.
dynamic test = conn.Query<dynamic>(sql);
// Step 2: Use Slapper.Automapper for mapping to the POCO Entities.
// - IMPORTANT: Let Slapper.Automapper know how to do the mapping;
// let it know the primary key for each POCO.
// - Must also use underscore notation ("_") to name parameters in the SQL query;
// see Slapper.Automapper docs.
Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestContact), new List<string> { "ContactID" });
Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestPhone), new List<string> { "PhoneID" });
var testContact = (Slapper.AutoMapper.MapDynamic<TestContact>(test) as IEnumerable<TestContact>).ToList();
foreach (var c in testContact)
{
foreach (var p in c.TestPhones)
{
Console.Write("ContactName: {0}: Phone: {1}\n", c.ContactName, p.Number);
}
}
}
}
,每个List<TestContact>
都有TestContact
。
Dapper和Slapper.Automapper都在内部缓存所有内容以提高速度。如果遇到内存问题(非常不可能),请确保偶尔清除这两个问题的缓存。
确保使用underscore (_
) notation为返回的列命名,以便为Slapper.Automapper提供有关如何将结果映射到POCO实体的线索。
确保为每个POCO实体的主键提供Slapper.Automapper线索(请参阅第List<TestPhone>
行)。您也可以在POCO上使用Slapper.AutoMapper.Configuration.AddIdentifiers
。如果你跳过这一步,那么它可能会出错(理论上),因为Slapper.Automapper不知道如何正确地进行映射。
成功将此技术应用于具有超过40个规范化表的庞大生产数据库。它完美地将超过16 Attributes
和inner join
的高级SQL查询映射到适当的POCO层次结构(具有4级嵌套)。查询速度非常快,几乎和在ADO.NET中手动编码一样快(查询通常为52毫秒,从平面结果到POCO层次结构的映射为50毫秒)。这实际上并不是革命性的,但它肯定比实体框架更快,更易于使用,特别是如果我们所做的只是运行查询。
代码在生产中运行了9个月完美无瑕。最新版本的left join
包含我应用的所有更改,用于修复与SQL查询中返回的空值相关的问题。
Code已经在生产中运行了21个月,并且已经处理了FTSE 250公司数百名用户的持续查询。
Slapper.Automapper
也非常适合将.csv文件直接映射到POCO列表中。将.csv文件读入IDictionary列表,然后将其直接映射到目标POCO列表中。唯一的技巧是你必须添加一个属性Slapper.Automapper
,并确保它对每一行都是唯一的(否则自动化程序无法区分行)。
轻微更新以添加更多代码注释。
答案 1 :(得分:13)
我希望尽可能简单,我的解决方案:
public List<ForumMessage> GetForumMessagesByParentId(int parentId)
{
var sql = @"
select d.id_data as Id, d.cd_group As GroupId, d.cd_user as UserId, d.tx_login As Login,
d.tx_title As Title, d.tx_message As [Message], d.tx_signature As [Signature], d.nm_views As Views, d.nm_replies As Replies,
d.dt_created As CreatedDate, d.dt_lastreply As LastReplyDate, d.dt_edited As EditedDate, d.tx_key As [Key]
from
t_data d
where d.cd_data = @DataId order by id_data asc;
select d.id_data As DataId, di.id_data_image As DataImageId, di.cd_image As ImageId, i.fl_local As IsLocal
from
t_data d
inner join T_data_image di on d.id_data = di.cd_data
inner join T_image i on di.cd_image = i.id_image
where d.id_data = @DataId and di.fl_deleted = 0 order by d.id_data asc;";
var mapper = _conn.QueryMultiple(sql, new { DataId = parentId });
var messages = mapper.Read<ForumMessage>().ToDictionary(k => k.Id, v => v);
var images = mapper.Read<ForumMessageImage>().ToList();
foreach(var imageGroup in images.GroupBy(g => g.DataId))
{
messages[imageGroup.Key].Images = imageGroup.ToList();
}
return messages.Values.ToList();
}
我仍然只对数据库进行一次调用,而我现在执行2次查询而不是1次,第二次查询使用INNER连接而不是最佳的LEFT连接。
答案 2 :(得分:7)
根据this answer,Dapper.Net中没有一对多的映射支持。查询将始终为每个数据库行返回一个对象。不过还有一种替代解决方案。
答案 3 :(得分:5)
稍微修改安德鲁的答案,利用Func选择父键而不是GetHashCode
。
public static IEnumerable<TParent> QueryParentChild<TParent, TChild, TParentKey>(
this IDbConnection connection,
string sql,
Func<TParent, TParentKey> parentKeySelector,
Func<TParent, IList<TChild>> childSelector,
dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
Dictionary<TParentKey, TParent> cache = new Dictionary<TParentKey, TParent>();
connection.Query<TParent, TChild, TParent>(
sql,
(parent, child) =>
{
if (!cache.ContainsKey(parentKeySelector(parent)))
{
cache.Add(parentKeySelector(parent), parent);
}
TParent cachedParent = cache[parentKeySelector(parent)];
IList<TChild> children = childSelector(cachedParent);
children.Add(child);
return cachedParent;
},
param as object, transaction, buffered, splitOn, commandTimeout, commandType);
return cache.Values;
}
使用示例
conn.QueryParentChild<Product, Store, int>("sql here", prod => prod.Id, prod => prod.Stores)
答案 4 :(得分:2)
这是一个粗略的解决方法
public static IEnumerable<TOne> Query<TOne, TMany>(this IDbConnection cnn, string sql, Func<TOne, IList<TMany>> property, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
var cache = new Dictionary<int, TOne>();
cnn.Query<TOne, TMany, TOne>(sql, (one, many) =>
{
if (!cache.ContainsKey(one.GetHashCode()))
cache.Add(one.GetHashCode(), one);
var localOne = cache[one.GetHashCode()];
var list = property(localOne);
list.Add(many);
return localOne;
}, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
return cache.Values;
}
它绝不是最有效的方式,但它会让你起作用。当我有机会的时候,我会尝试优化它。
像这样使用它:
conn.Query<Product, Store>("sql here", prod => prod.Stores);
请记住,您的对象需要实现GetHashCode
,或许像这样:
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
答案 5 :(得分:1)
这是另一种方法:
订单(一个)-OrderDetail(许多)
using (var connection = new SqlCeConnection(connectionString))
{
var orderDictionary = new Dictionary<int, Order>();
var list = connection.Query<Order, OrderDetail, Order>(
sql,
(order, orderDetail) =>
{
Order orderEntry;
if (!orderDictionary.TryGetValue(order.OrderID, out orderEntry))
{
orderEntry = order;
orderEntry.OrderDetails = new List<OrderDetail>();
orderDictionary.Add(orderEntry.OrderID, orderEntry);
}
orderEntry.OrderDetails.Add(orderDetail);
return orderEntry;
},
splitOn: "OrderDetailID")
.Distinct()
.ToList();
}
来源:http://dapper-tutorial.net/result-multi-mapping#example---query-multi-mapping-one-to-many