无法找出Linq加入

时间:2017-11-15 15:59:56

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

在LinqPad中,我有这个工作,基础SQL查询就是我想要的:

from userProcesses in UserProcesses
join formProcesses in FormProcesses 
   on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms 
    on formProcesses.Form_FormID equals forms.FormID
join userForms in UserForms
    on new {userProcesses.UserProcessID, forms.FormID} equals 
       new {userForms.UserProcessID, userForms.FormID} into combined
from c in combined.DefaultIfEmpty()
select new
{
    UserFormID = c == null ? (int?) null : c.UserFormID,
    FormID = forms.FormID,
    Name = forms.Name
}

问题是,在我的实际代码中,FormProcesses表本身并未公开,而是一个导航属性。我一直在努力学习如何在我的软件中编写此查询。

以下是我的模型的骨架视图,以便您可以看到导航属性:

public class UserProcess : BaseModel
    {
        [Key]
        public int UserProcessID { get; set; }

        [Required]
        [ForeignKey("Process")]
        public int ProcessID { get; set; }

        public Process Process { get; set; }

        public virtual ICollection<UserForm> UserForms { get; set; }
    }

 public class Form : Common.BaseModel
    {
        [Key]
        public int FormID { get; set; }       

        public virtual ICollection<Process> Processes { get; set; }
    }

public class UserForm : Common.BaseModel
    {
        [Key]
        public int UserFormID { get; set; }

        [Required]
        [ForeignKey("UserProcess")]
        public int UserProcessID { get; set; }

        public UserProcess UserProcess { get; set; }

        [Required]
        [ForeignKey("Form")]
        public int FormID { get; set; }

        public Form Form { get; set; }
    }

public class Process : Common.BaseModel
    {
        [Key]
        public int ProcessID { get; set; }

        public virtual ICollection<Form> Forms { get; set; }
    }

我做错了什么 - 我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:1)

您可以通过导航属性“导航”替换所有显式连接。

例如,以下加入

join formProcesses in FormProcesses
    on userProcesses.ProcessID equals formProcesses.Process_ProcessID
join forms in Forms
    on formProcesses.Form_FormID equals forms.FormID

成为:

from forms in userProcesses.Process.Forms

应解决相关问题。

(可选)LINQ to Entities编写以下连接的方式:

join userForms in UserForms
    on new { userProcesses.UserProcessID, forms.FormID } equals
       new { userForms.UserProcessID, userForms.FormID } into combined

是:

let combined = from userForms in userProcesses.UserForms
               where userForms.FormID == forms.FormID
               select userForms