这是我的工作代码:
string query = @"SELECT DISTINCT
up.id as unitId,
af.id as fileId,
af.reference_id as referenceId,
af.filename as fileName,
af.filepath as filePath,
c.id as categoryId
u.id as userId
FROM unit_properties up
INNER JOIN categories c ON up.category_id = c.id
INNER JOIN users u ON up.agent_id = u.id
LEFT JOIN app_files af ON af.reference_id = up.id;";
var unitProperties = await connection.QueryAsync<UnitProperty, AppFile, Category, User, UnitProperty>(
query,
(unit, appFile, category, user) =>
{
unit.UnitImages = appFile;
unit.UnitCategory = category;
unit.UnitAgent = user;
return unit;
},
splitOn: "referenceId, categoryId, userId"
);
唯一的问题是,当有多个
unitImages
附加到unit_properties时,该函数返回两个相同的行。
**unitID 1 重复
[
{
"unitId":1,
"unitImages":{
"fileId":0,
"referenceId":1,
"fileName":"exterior1",
"filePath":"exterior1"
},
"unitAgent":{
"userId":1
},
"unitCategory":{
"categoryId":1
}
},
//another object same as above
]
我需要这样的东西:
"unitId":1,
"unitImages":[
{
"fileId":0,
"referenceId":1,
"fileName":"exterior1",
"filePath":"exterior1"
},
{
"fileId":1,
"referenceId":1,
"fileName":"exterior2",
"filePath":"exterior2"
}
],
任何代码建议都将受到高度赞赏。谢谢你。
public class Group
{
public int Id { get; set; }
public string Group_Name { get; set; }
public ICollection<Student> Students { get; set; }
}
学生.cs
public class Student
{
public int Student_Id { get; set; }
public string Student_Name { get; set; }
public int Group_Id { get; set; }
}
查询
[HttpGet]
public async Task<IActionResult> test()
{
using (var connection = new SqlConnection("Server = 192.168.2.68; Database = test1; User Id = sa; Password = xxxxx;"))
{
var groupDictionary = new Dictionary<int, Group>();
string sql = "SELECT * FROM GroupTable A INNER JOIN StudentTable B ON A.Id = B.Group_Id;";
var orders = connection.Query<Group, Student, Group>(sql,
(group, student) =>
{
var groupEntry=new Group();
if (!groupDictionary.TryGetValue(group.Id, out groupEntry))
{
groupEntry = group;
groupEntry.Students = new List<Student>();
groupDictionary.Add(groupEntry.Id, groupEntry);
}
groupEntry.Students.Add(student);
return groupEntry;
},splitOn:"Student_Id").Distinct();
return Ok(orders);
}
}