1

使用 SQL,我将执行以下操作...

SELECT G.* FROM GOAL G
INNER JOIN Plan P ON
P.planID = G.planID
INNER JOIN User U ON
U.userID = P.userID
WHERE U.userID = @userID

在我的控制器(MVC4)"ActionResult Edit"中,我执行以下操作,这是两个查询,我怎么能只做一个?目标是确保用户只能对自己的数据执行“编辑”操作,而不是其他人的目标。

var plan = db.Plan.Where(b => b.UserID == CurrentUserID).FirstOrDefault();
Goal goal = db.Goals
            .Where(b => b.PlanID == plan.ID)
            .FirstOrDefault();
return View(goal);

模型

public class Plan
{
    public int ID { get; set; }
    [Required]
    public int UserID { get; set; }
}
[Table("PlanGoal")]
public class Goal
{
    public int ID { get; set; }

    [Required]
    public int PlanID { get; set; } 
}
4

2 回答 2

2

虚拟 Plan属性添加到Goal

public class Goal
{
    public int ID { get; set; }        
    public virtual Plan Plan { set;get;}    
    [Required]
    public int PlanID { get; set; } 
}

现在你可以像这样查询它

Goal goal = db.Goals
            .Where(b => b.Plan.UserID == CurrentUserID).FirstOrDefault();
于 2012-09-13T22:53:06.783 回答
1

或者您可以将目标和计划结合在一起,而不是在您的Goal课程中添加属性:

Goal goal = (from g in db.Goals
            from p in db.Plan
            where p.UserID == CurrentUserID
             && g.PlanID == p.ID
            select g).FirstOrDefault();
于 2012-09-13T23:08:29.827 回答