如何使用Dapper映射嵌套对象列表

我目前正在使用Entity Framework进行数据库访问,但想看看Dapper。我有这样的课程:


public class Course{

   public string Title{get;set;}

   public IList<Location> Locations {get;set;}

   ...

}


public class Location{

   public string Name {get;set;}

   ...

}

因此,可以在多个位置教授一门课程。Entity Framework为我执行了映射,因此我的Course对象中填充了位置列表。我将如何使用Dapper做到这一点,甚至有可能还是我必须在几个查询步骤中做到这一点?


慕哥6287543
浏览 992回答 3
3回答

繁花不似锦

无需lookup字典var coursesWithLocations =&nbsp;&nbsp; &nbsp; conn.Query<Course, Location, Course>(@"&nbsp; &nbsp; &nbsp; &nbsp; SELECT c.*, l.*&nbsp; &nbsp; &nbsp; &nbsp; FROM Course c&nbsp; &nbsp; &nbsp; &nbsp; INNER JOIN Location l ON c.LocationId = l.Id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ", (course, location) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; course.Locations = course.Locations ?? new List<Location>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; course.Locations.Add(location);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return course;&nbsp; &nbsp; &nbsp; &nbsp; }).AsQueryable();
打开App,查看更多内容
随时随地看视频慕课网APP