我有两个表格,其中包含兽医数据。
客户有很多病人(病人),关系是“一对多”的。 我想给客户显示他们的宠物名,并单行计数
表格:客户
public class Customer
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
}
表格:患者(宠物)
public class Patient
{
[Key]
public int PatientID { get; set; }
public bool IsActive { get; set; }
public int TypePatientID { get; set; }
public string TypeRace { get; set; }
public string CIPCode { get; set; }
public string Color { get; set; }
public string PatientName { get; set; }
public int Status { get; set; }
public int GenderID { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? DeathDate { get; set; }
public int CustomerID { get; set; }
public int AccountID { get; set; }
}
public class CustomerPageModel
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
public string Pats { get; set; }
public int PatCount { get; set; }
}
我尝试了以下代码:
var result = from p in context.Customers
join f in context.Patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group f by new { f.CustomerID, p.IsActive, p.TC, p.Name, p.Surname, p.Email, p.Address, p.Phone, p.Note, p.AccountID, f.PatientName,p.ID } into g
select new CustomerPageModel
{
ID=g.Key.ID,
IsActive = g.Key.IsActive,
TC = g.Key.TC,
Name = g.Key.Name,
Surname = g.Key.Surname,
Email = g.Key.Email,
Address = g.Key.Address,
Phone = g.Key.Phone,
Note = g.Key.Note,
AccountID = g.Key.AccountID,
Pats = string.Join(",", g.Select(x => x.PatientName))
};
预期结果是:
[
{
"id":13,
"isActive":true,
"tc":"1234",
"name":"John ",
"surname":"Snow",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Oscar,Puffy",
"patCount":2
},
{
"id":14,
"isActive":true,
"tc":"2345",
"name":"Mark",
"surname":"Zurk",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Mars",
"patCount":1
}
]
请检查链接: https://dotnetfiddle.net/rsv45D
有人可以帮我写这个ef查询吗?
答案 0 :(得分:0)
为什么要按所有字段分组,因为您只想按应为CustomerID(或其关键字段为任何用户)的用户分组:
var result = from p in customers
join f in patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group new { f, p } by f.CustomerID into g
select new CustomerPageModel
{
ID = g.Key,
IsActive = g.First().p.IsActive,
TC = g.First().p.TC,
Name = g.First().p.Name,
Surname = g.First().p.Surname,
Email = g.First().p.Email,
Address = g.First().p.Address,
Phone = g.First().p.Phone,
Note = g.First().p.Note,
AccountID = g.First().f.AccountID,
Pats = string.Join(",", g.Select(x => x.f.PatientName)),
PatCount = g.Count()
};