我从未使用过JOIN。什么时候适当?

时间:2017-01-25 12:01:07

标签: asp.net-mvc linq join

我从未使用JOIN(INNER, OUTER),而且我不知道什么时候是最好的情景:

我在这里有两个使用2个或3个查询来获取对象的ActionResults示例,而不是使用JOIN更好吗?

第一个例子:

public ActionResult JobTags(int id)
{
   var jobTagsList = (from j in db.JobTags
                           where j.JobID == id
                           select j.TagID).ToList();

   var tags = (from j in db.Tags
                    where jobTagsList.Contains(j.ID.ToString())
                    select j).ToList();

   return View(tags);
}

我可以JOIN这两个表并在结尾处选择j吗?

第二个例子:

public ActionResult ImageListWhoApp(int id)
{
    //We get here the ID from Job page using dbo.Jobs
    var userIdList = (from j in db.Jobs
                           where j.ID == id
                           select j.ID.ToString()).ToList();

    //We get here who applied at this job using dbo.AppliedJobs
    var appJobIdList = (from j in db.AppliedJobs
                    where userIdList.Contains(j.JobID.ToString())
                    select j.UserID).ToList();

    //Finally we get here the avatars of the user who applied at the job
    //We are using this as a hyperlink to user profile.
    var appUserImage = (from j in db.Images
                            where appJobIdList.Contains(j.UserID.ToString())
                            select j).ToList();

    return View(appUserImage);
}

这种做法不是很荒谬吗?或者以这种方式做这样的事情是正常的吗?如何从这3个JOIN语句中创建SQL?可能吗?这是更好的方式吗?

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

您不需要加入。您可以使用导航属性:

var tagsQry =
    from tag in db.Tags
    where tag.JobTag.JobID == id
    select tag;

var userImageQry =
    from img in db.Images
    from appJob in db.AppliedJobs
    where (img.UserID == appJob.UserID) && (appJob.Job.ID == id)
    select img;

即使您没有导航属性,也不需要加入:

var tagsQry =
    from tag in db.Tags
    from jobTag in sb.JobTags
    where (jobTag.JobID == id) && (tag.ID == jobTag.TagID)
    select tag;

var userImageQry =
    from img in db.Images
    from appJob in db.AppliedJobs
    from job in db.Jobs
    where (img.UserID == appJob.UserID) && (appJob.JobID == job.ID) && (job.ID == id)
    select img;

如果您更喜欢语法,则可以使用联接。数据库端查询执行计划将完全相同:

var tagsQry =
    from tag in db.Tags
    join jobTag in sb.JobTags on tag.ID equals jobTag.TagID
    where (jobTag.JobID == id)
    select tag;

var userImageQry =
    from appJob in db.AppliedJobs
    join img in db.Images on appJob.UserID equals img.UserID
    join job in db.Jobs on appJob.JobID equals job.ID
    where (job.ID == id)
    select img;

在第二个示例中,如果您在Jobs上没有外键约束,则只需要AppliedJobs.JobID的查询(或加入)。如果您这样做,可以直接将AppliedJobs.JobIDid进行比较。