我需要一些关于如何使用Dapper将数据导入多个列表对象,然后将列表序列化为适当的JSON格式的建议。请分享您的建议。谢谢!
1。样本JSON格式
{
"students": [
{
"studentId": "",
"emailAddresses": [
{
"emailAddress": ""
}
],
"lastName": "",
"directory": {
"addresses": [
{
"city": "",
"state": ""
}
],
}
}
]
}
2。类
public class Student
{
public string StudentId { get; set; }
public string Gender { get; set; }
public List<EmailAddresses> emailAddresses { get; set; }
}
public class EmailAddresses
{
public string EmailAddress { get; set; }
}
第3。来自sql查询的数据
StudentId Gender EmailAddress
123456 Female maryjoe@gmail.com
123456 Female mary.joe@mycollege.edu
123456 Female mj@hotmail.com
4。我正在尝试实施的Dapper代码
public List<Student> GetStudentData()
{
List<Student> dataStudent;
using (IDbConnection connection = RepositoryHelper.OpenConnection())
{
dataStudent = connection.Query<Student, EmailAddresses, Student>("mystoredprocedure",
(c, cc) =>
{
c.EmailAddresses = cc;
return c;
}, splitOn: "EmailAddress").ToList();
}
return dataStudent;
}
4。序列化为JSON
static void Main(string[] args)
{
List<Student> students = GetStudentData();
var json = new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(students);
}
答案 0 :(得分:1)
第一个问题是您在调用存储过程时未指定命令类型是存储过程。这会将您的proc名称错误地转换为sql命令,这显然会失败。
但是,根据您更新的评论,第二个问题是您误用了dapper的多映射器功能。此功能用于将多个表映射到多个对象。但是,您的存储过程似乎为您提供了一个展平对象,您需要根据学生ID拆分唯一记录,将电子邮件地址映射到您的电子邮件地址属性。
动态效果非常好,因为我们可以即时映射数据。
public List<Student> GetStudentData()
{
List<Student> dataStudent;
using (IDbConnection connection = RepositoryHelper.OpenConnection())
{
dataStudent = connection.Query<dynamic>(
"mystoredprocedure",
commandType: CommandType.StoredProcedure)
.GroupBy(x => x.StudentId)
.Select(x => new Student
{
StudentId = x.First().StudentId,
Gender = x.First().Gender,
emailAddresses = x.Select(ea => new EmailAddresses
{
EmailAddress = ea.emailAddresses
}).ToList()
}).ToList();
return dataStudent;
}
}