我有一个Application Object,其中包含Applicant对象。申请人对象有雇员对象,其中包含有关就业的所有信息(姓名,地址,......),这可以是0或2,3,4,......我如何获得1个申请的Emp of Count?所以在这种情况下,它必须返回4.但我的代码返回2,因为它返回每个申请人的计数而不是申请。
这是我的代码:
public void InsertApplication(Application application)
{
if (application.Applicants != null)
{
foreach (var item in application.Applicants)
{
if (item.Employments != null)
{
application.NumberOfEmployments = item.Employments.Count();
}
}
}
creditApplicationsContext.Applications.Add(application);
}
这是应用程序对象:
public class Application
{
public int Id { get; set; }
public virtual ICollection<Applicant.Applicant> Applicants { get; set; }
public int? NumberOfEmployments { get; set; }
这是申请人对象:
public class Applicant
{
public int Id { get; set; }
public virtual ICollection<Employment> Employments { get; set; }
....
}
这是就业对象:
public class Employment
{
public int Id { get; set; }
public string EmployerName { get; set; }
public string EmployerPhoneNumber { get; set; }
public Applicant Applicant { get; set; }
.....
}
答案 0 :(得分:5)
如果我正确理解您的结构,您应该能够使用相当简单的SelectMany
和Count
:
application.Applicants.SelectMany(a => a.Employments).Count();
答案 1 :(得分:2)
嗯,你几乎就在那里,问题是你要替换每个子节点的值,而不是添加它。
更改为:
public void InsertApplication(Application application)
{
application.NumberOfEmployments = 0;
if (application.Applicants != null)
{
foreach (var item in application.Applicants)
{
if (item.Employments != null)
{
application.NumberOfEmployments += item.Employments.Count();
}
}
}
creditApplicationsContext.Applications.Add(application);
}
答案 2 :(得分:2)
SelectMany
可以提供帮助:
application.Applicants.SelectMany(x => x.Employments).Count();
答案 3 :(得分:2)
您可以添加一个方法来获取应用程序数量并使用SelectMany
public class Application
{
public int Id { get; set; }
public virtual ICollection<Applicant> Applicants { get; set; }
public int? NumberOfEmployments { get; set; }
public int GetNumberOfApplications()
{
return this.Applicants.SelectMany(x => x.Employments).Count();
}
}
答案 4 :(得分:1)
application.NumberOfEmployments =
application.Sum(app1 => app1.Applicants.Sum(app2 => app2.Employments.Count()));
答案 5 :(得分:1)
要获得代码的总数,请在代码中考虑此更改:
public void InsertApplication(Application application)
{
if (application.Applicants != null)
{
foreach (var item in application.Applicants)
{
if (item.Employments != null)
{
application.NumberOfEmployments += item.Employments.Count();
}
}
}
creditApplicationsContext.Applications.Add(application);
}
通过这种方式,您可以获得就业总数。 我认为你的代码返回2是因为是最后一个应用程序的就业数量。