EF LINQ查询,用于在单行中选择多个表并计数
我有两张表,上面有兽医的数据 客户有许多患者(PAT),关系是“一对多”。 我想向客户展示他们的petsname和单行计数 表格:客户EF LINQ查询,用于在单行中选择多个表并计数,linq,group-by,inner-join,Linq,Group By,Inner Join,我有两张表,上面有兽医的数据 客户有许多患者(PAT),关系是“一对多”。 我想向客户展示他们的petsname和单行计数 表格:客户 public class Customer { [Key] public int ID { get; set; } public bool IsActive { get; set; } public string TC { get; set; } public string
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; }
}
表格:患者(Pet)
我尝试了以下代码:
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
}
]
请查看链接:
有人能帮我写这个ef查询吗?为什么要按所有字段分组,因为您只想按应该是CustomerID(或其关键字段是什么)的用户分组:
如果我不将其他字段分组,则该字段不在g@RaptorR
groupf按new{f.CustomerID,p.IsActive,p.TC,p.Name,p.姓氏,p.Email,p.Address,p.Phone,p.Note,p.AccountID,f.PatientName,p.ID}进入g
new{}Mobayen中的所有字段都会显示它,我忘记了一个情况,如果动物不来,客户就不会来列表,那么我如何才能进行左侧加入?混合组bythen merge with x.PatCount=0?我查看了代码,它不应该显示任何没有宠物的客户,它只会显示那些有宠物的客户,只是测试一下。
[
{
"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
}
]
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()
};