【问题标题】:Entity framework - right join to a view实体框架 - 右连接到视图
【发布时间】:2014-10-15 17:18:42
【问题描述】:

我的数据库上下文中有 2 个实体:

员工
EmployeeHolidayEntitlement

认为这是一种相当正常的一对一关系 - 但 Employee 可以在没有 EmployeeHolidayEntitlement 的情况下存在,但 EmployeeHolidayEntitlement 不能在没有 Employee 的情况下存在

Employee 被映射到我数据库中的 视图
EmployeeHolidayEntitlement 是一个表格

我的课程是:

EmployeeHolidayEntitlement

[Table("tblEmployeeHolidayEntitlement")]
public class EmployeeHolidayEntitlement
{
    [Key]
    public int EmployeeNumber { get; set; }

    public virtual Employee Employee { get; set; }

    public decimal StandardEntitlement { get; set; }

    //.....omitted for brevity
}

员工

[Table("vEmployee")] //note v - it's a view
public class Employee
{
    [Key]
    public int EmployeeNumber { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

在构建上下文时,我会:
(不确定这是否正确!)

modelBuilder.Entity<EmployeeHolidayEntitlement>()
  .HasRequired(w => w.Employee)
  .WithOptional();

查询时,如果可能的话,我希望每个员工都有一个 EmployeeEntitlement 记录(不管它是否存在于 tblEmployeeHolidayEntitlement 中) -

我的查询目前如下所示:

from
    userEntitlement in db.ADUserHolidayEntitlement
 join
    adUser in db.ADUsers
    on
    userEntitlment.EmployeeNumber equals adUser.EmployeeNumber
select userEntitlement

但这是(我认为)进行左连接 - 它只返回在 tblEmployeeHolidayEntitlement 中有条目的 2 个实体

我想生成的 SQL 需要看起来像:

SELECT 
employee.EmployeeNumber, 
employeeHol.* 

FROM tblEmployeeHolidayEntitlement employeeHol

RIGHT JOIN vEmployee employee
ON 
employeeHol.EmployeeNumber = employee.EmployeeNumber

这可能吗?

【问题讨论】:

    标签: c# sql linq entity-framework


    【解决方案1】:

    您的代码正在执行内部连接。我相信您要求检索所有员工,并为每个员工提供一个EmployeeHolidayEntitlement(如果存在)。

    要执行左连接,请使用类似以下的查询:

    from adUser in db.ADUsers
    join userEntitlement in db.ADUserHolidayEntitlement on
        adUser.EmployeeNumber equals userEntitlment.EmployeeNumber into g
    from userEntitlement in g.DefaultIfEmpty()
    select new 
    {
        adUser, 
        userEntitlement // Will be null of no entitlement exists
    }
    

    【讨论】:

      【解决方案2】:

      它按照您的要求进行内部连接。

      您根本不需要显式连接。

      你需要这样的东西:

      from user in db.....
      select new{user,user.Entitlement};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-15
        • 2015-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多