我已经编写了这个代码来实现一对多的关系,但它不起作用:
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>
有什么问题。
这篇文章展示了如何查询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
处理任意嵌套的层次结构,它不仅限于几个级别的嵌套。我们可以轻松地进行快速更改,一切都将继续。inner join
创建扁平化查询以返回平面结果比创建多个select语句容易,在客户端进行拼接。select
(它带回来重复)来展平它,我们应该使用多个Slapper.Automapper语句并将所有东西重新拼接在一起在客户端(请参阅本页的其他答案)。在我的测试中,Dapper by itself
为Dapper返回的结果添加了一小部分开销,这意味着它仍然比实体框架快10倍,并且组合仍然非常接近SQL + C#能够达到的理论最大速度。
在大多数实际情况中,大部分开销都是在一个不太理想的SQL查询中,而不是在C#端对结果进行一些映射。
迭代总数:1000
3 lines of code to return the dynamic
:每个查询1.889毫秒,使用Dapper + Slapper.Automapper
。3 lines of code for the query + mapping from dynamic to POCO Entities
:每个查询2.463毫秒,使用额外的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
请注意,此表有一个外键TestContact
,它指的是List<TestPhone>
表(这对应于上面POCO中的JOIN
)。
在我们的SQL查询中,我们使用尽可能多的flat, denormalized form语句来获取我们需要的所有数据,在Slapper.Automapper中。是的,这可能会在输出中产生重复,但是当我们使用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
自动将此查询的结果直接映射到我们的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>
在Visual Studio中,我们可以看到Slapper.Automapper正确地填充了我们的POCO实体,即我们有一个TestContact
,每个List<TestPhone>
都有一个underscore (_
) notation。
Dapper和Slapper.Automapper都在内部缓存所有内容以提高速度。如果遇到内存问题(非常不可能),请确保偶尔清除这两个问题的缓存。
确保使用Slapper.AutoMapper.Configuration.AddIdentifiers
为返回的列命名,以便为Slapper.Automapper提供有关如何将结果映射到POCO实体的线索。
确保为每个POCO实体的主键提供Slapper.Automapper线索(请参阅Attributes
行)。您也可以在POCO上使用inner join
。如果你跳过这一步,那么它可能会出错(理论上),因为Slapper.Automapper不会知道如何正确地进行映射。
成功将此技术应用于具有40多个规范化表的庞大生产数据库。它完美地将超过16个left join
和Slapper.Automapper
的高级SQL查询映射到适当的POCO层次结构(具有4级嵌套)。查询速度非常快,几乎和在ADO.NET中手动编码一样快(查询通常为52毫秒,从平面结果到POCO层次结构的映射为50毫秒)。这实际上并不是革命性的,但它肯定胜过实体框架的速度和易用性,特别是如果我们所做的只是运行查询。
代码在生产中运行了9个月完美无瑕。最新版本的Slapper.Automapper
具有我用于修复与SQL查询中返回的空值相关的问题的所有更改。
Code已经在生产中运行了21个月,并且已经处理了FTSE 250公司数百名用户的持续查询。
int Id {get; set}
也非常适合将.csv文件直接映射到POCO列表中。将.csv文件读入IDictionary列表,然后将其直接映射到目标POCO列表中。唯一的技巧是你必须添加一个属性https://github.com/SlapperAutoMapper/Slapper.AutoMapper,并确保它对每一行都是唯一的(否则自动化器将无法区分行)。
轻微更新以添加更多代码注释。
见: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();
}
根据GetHashCode
的说法,Dapper.Net中没有一对多的映射支持。查询将始终为每个数据库行返回一个对象。但是,还有一个替代解决方案。
稍微修改安德鲁的答案,利用Func选择父键而不是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)
用法示例
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();
}
,也许是这样的:
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();
}
这是另一种方法:
订单(一) - OrderDetail(很多)
http://dapper-tutorial.net/result-multi-mapping#example---query-multi-mapping-one-to-many
资料来源:qazxswpoi