问题描述
我目前正在使用实体框架来访问我的数据库,但想看看 Dapper.我有这样的课程:
I'm currently using Entity Framework for my db access but want to have a look at Dapper. I have classes like this:
public class Course{
public string Title{get;set;}
public IList<Location> Locations {get;set;}
...
}
public class Location{
public string Name {get;set;}
...
}
因此可以在多个地点教授一门课程.实体框架为我做映射,所以我的 Course 对象填充了一个位置列表.我将如何使用 Dapper 解决这个问题,它甚至可能还是必须在多个查询步骤中完成?
So one course can be taught at several locations. Entity Framework does the mapping for me so my Course object is populated with a list of locations. How would I go about this with Dapper, is it even possible or do I have to do it in several query steps?
推荐答案
Dapper 不是一个完整的 ORM,它不处理神奇的查询生成等.
Dapper is not a full blown ORM it does not handle magic generation of queries and such.
对于您的特定示例,以下可能有效:
For your particular example the following would probably work:
var courses = cnn.Query<Course>("select * from Courses where Category = 1 Order by CreationDate");
抓取相关映射:
var mappings = cnn.Query<CourseLocation>(
"select * from CourseLocations where CourseId in @Ids",
new {Ids = courses.Select(c => c.Id).Distinct()});
抓取相关位置
var locations = cnn.Query<Location>(
"select * from Locations where Id in @Ids",
new {Ids = mappings.Select(m => m.LocationId).Distinct()}
);
全部映射
将此留给读者,您可以创建一些地图并遍历包含位置的课程.
Map it all up
Leaving this to the reader, you create a few maps and iterate through your courses populating with the locations.
警告 in
技巧将起作用,如果您的数量少于 2100 个查找(Sql Server),如果您有更多查找,您可能希望将查询修改为 select * from CourseLocations where CourseId in (select Id来自 Courses ... )
如果是这种情况,您也可以使用 QueryMultiple
Caveat the in
trick will work if you have less than 2100 lookups (Sql Server), if you have more you probably want to amend the query to select * from CourseLocations where CourseId in (select Id from Courses ... )
if that is the case you may as well yank all the results in one go using QueryMultiple
这篇关于如何使用 Dapper 映射嵌套对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!