Dapper如何加载完整对象树

时间:2017-04-17 08:46:31

标签: sql asp.net-mvc orm dapper dapper-extensions

对于我正在使用Dapper ORM的新项目。我还安装了Contrib软件包,但当我对对象进行操作时,我没有获得任何关系对象。

如何完全加载具有所有级别的对象?

我的对象示例(较短版本):

public class Profile
{
    public int Id { get; set; }

    public List<Review> Reviews { get; set; }
    public List<ProfileCategory> Categories { get; set; }
}

public class ProfileCategory
{
    public int Id { get; set; }

    public Profile Profile { get; set; }
    public Category Category { get; set; }
}

public class Category
{
    public int Id { get; set; }
}

public class Review
{
    public int Id { get; set; }

    public Profile Profile { get; set; }
}

查询:

const string sql = "SELECT * FROM Profile WHERE Id = @Id; " +
                           "SELECT * FROM ProfileCategory WHERE IdProfile = @Id; " +
                           "SELECT * FROM ProfileAttachment WHERE IdProfile = @Id; " +
                           "SELECT * FROM Opening WHERE IdProfile = @Id; " +
                           "SELECT * FROM Review WHERE IdProfile = @Id";

        using (var multipleResults = _db.QueryMultiple(sql, new { Id = id }))
        {
            var profile = multipleResults.Read<Profile>().SingleOrDefault();
            var categories = multipleResults.Read<ProfileCategory>().ToList();
            var attachments = multipleResults.Read<ProfileAttachment>().ToList();
            var openings = multipleResults.Read<Opening>().ToList();
            var reviews = multipleResults.Read<Review>().ToList();

            profile?.Categories.AddRange(categories);
            profile?.Pictures.AddRange(attachments);
            profile?.OpeningHours.AddRange(openings);
            profile?.Reviews.AddRange(reviews);

            return profile;
        }

我设法进行此查询,但这不会加载ProfileCategory中的类别。我可以加载所有级别吗?

我是Dapper的新手,非常感谢任何帮助!

0 个答案:

没有答案