0

这是我的课

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);
          }
     }
}  
  1. 实体框架加载 Employee 和 Salaries 属性。
  2. CanAddSalary 方法只是检查以避免重复(没有修改 Salaries Collection 对吗?)。
  3. 如果 CanAddSalary 返回 true,那么我调用 AddSalary 方法。
  4. 我调用 Entity Framework Context.SaveChanges() 并抛出异常。
4

2 回答 2

0

You should use == instead of = in your return statement, because otherwise you'll always get false from CanAddSalary method:

 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;
 }
于 2013-04-10T05:58:12.973 回答
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);
      }
 }
}  
于 2013-04-10T06:09:45.383 回答