实体框架 - 选择可以为空的连接属性

时间:2012-03-28 09:24:11

标签: sql linq entity-framework-4 linq-to-entities

我的表格结构如下:

Account
 AccountId
 LoginName
 EmployeeId - nullable
Employee
  FirstName,
  SecondName,
  etc..

我有疑问:

   var data = from o in _accountRepository.AsQueryableWithIncludes(x => x.Employee, x => x.Permissions)
               select new AccountGridVM
               {
                   AccountId = o.AccountId,
                   EmployeeFirstName = o.EmployeeId == null ? String.Empty: o.Employee.FirstName,
                   LoginName = o.LoginName,
                   Permissions = o.Permissions.Select(s => s.NameCZ)
               };
    return View(new GridModel { Data = data });

我的问题是在EmployeeFirstName的tenar运算符中,实体框架总是只提取具有employeeId赋值的帐户,但我需要获取所有帐户。

如果我删除EmployeeFirstName propeprty,则ef获取所有行。

问题在哪里?

由于

1 个答案:

答案 0 :(得分:1)

问题解决了。我在绘图时遇到了错误。

  //bad
  HasRequired(x => x.Employee).WithMany().HasForeignKey(x => x.EmployeeId); // inner join

  //good
  HasOptional(x => x.Employee).WithMany().HasForeignKey(x => x.EmployeeId); // left join