dapper多对一映射

时间:2017-08-28 07:36:18

标签: c# mapping dapper

我有以下sql server查询:

ALTER PROC [dbo].[GetStudentBySchoolGrade]
(@GradeId INT = NULL, @SchoolId INT = NULL)
AS
SELECT 
StudentId,
Firstname,
Surname,
[DateOfBirth],
S.[GenderId],
S.[GradeId],
S.[SchoolId],
[GenderName],
[GradeName],
[GradeCode],
GR.[SchoolId], 
SC.[SchoolId],
[SchoolName],
[SchoolCode],
[Location]
FROM Students S
inner join School SC ON S.SchoolId = SC.SchoolId
inner join Grades GR ON S.GradeId = Gr.GradeId
inner join Gender G ON S.GenderId = G.GenderId
WHERE ((S.GradeId IS NULL) OR S.GradeId = @GradeId) OR
((@SchoolId IS NULL ) OR S.SchoolId =  @SchoolId)

注意:成绩是指级别(与学生成绩无关)

我在C#中使用Dapper进行了以下映射:

var parameter = new DynamicParameters();
parameter.Add("@SchoolId", schoolId);
parameter.Add("@GradeId", gradeId);
var students = connectionManager.Connection.Query<Student, Gender, Grade, School, Student>("GetStudentBySchoolGrade",
                (student, gender, grade, school) =>
                 {
                     student.Gender = gender;
                     student.Grade = grade;                   
                     student.School = school;
                     return student;
                 },
                splitOn: "GenderId,GradeId,SchoolId", param: parameter, commandType: CommandType.StoredProcedure);
return students;

执行查询后我得到的结果有一些丢失的对象,即使查询中有数据,Gender也为null。我的映射有什么问题吗?

以下是我的POCO课程:

等级

public partial class Grade
{
     public Grade()
    {
        Students = new HashSet<Student>();
    }

    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string GradeCode { get; set; }
    public int SchoolId { get; set; }
    public virtual School School { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

性别

public partial class Gender
{
    public Gender()
    {
        Students = new HashSet<Student>();
    }

    public int GenderId { get; set; }
    public string GenderName { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

学校

 public partial class School
{
   public School()
    {
        Grades = new HashSet<Grade>();
        Students = new HashSet<Student>();
    }
    public int SchoolId { get; set; }
    public string SchoolName { get; set; }
    public string SchoolCode { get; set; }
    public string Location { get; set; }
    public virtual ICollection<Grade> Grades { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

学生

 public partial class Student
{
    public int StudentId { get; set; }
    public string Firstname { get; set; }
    public string Surname { get; set; }
    public int GenderId { get; set; }
    public int? GradeId { get; set; }
    public int? SchoolId { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public virtual Gender Gender { get; set; }
    public virtual Grade Grade { get; set; }
    public virtual School School { get; set; }
}

0 个答案:

没有答案