这是我的班级
public class Employee
{
public virtual List<Salary> Salaries { get; set; }
public bool CanAddSalary(Salary salary)
{
var count = (from x in Salaries where x.Month == salary.Month
&& x.Year == salary.Year select x).Count();
return count == 0;
}
public void AddSalary(Salary salary)
{
if(CanAddSalary(salary))
{
Salaries.Add(salary);
}
}
}
答案 0 :(得分:0)
您应该在return语句中使用==
而不是=
,否则您将始终从false
方法获得CanAddSalary
:
public bool CanAddSalary(Salary salary)
{
var count = (from x in Salaries where x.Month == salary.Month
&& x.Year == salary.Year select x).Count();
return count == 0;
}
答案 1 :(得分:0)
你的工资应该是
ICollection<Salary>
并且执行Any()将比执行Count()
更快您
return count = 0;
错误意味着
Salaries.Add(salary);
正在添加工资集合中已有的工资,这可能是例外
试试这个,如果你仍然得到异常,那么也在这里发布,所以我们可以看到错误
欢呼声 斯图
public class Employee
{
public virtual ICollection<Salary> Salaries { get; set; }
public bool CanAddSalary(Salary salary)
{
return !(from x in Salaries where x.Month == salary.Month
&& x.Year == salary.Year select x).Any();
}
public void AddSalary(Salary salary)
{
if(CanAddSalary(salary))
{
Salaries.Add(salary);
}
}
}