EF Where子句以及当前用户ID

时间:2019-01-06 01:21:24

标签: entity-framework

我有一个ViewModel,它既需要包含有关当前用户的所有详细信息,也需要包含有关他们所注册的计划的所有详细信息:

public class SubscribeViewModel
{
    public ApplicationUser User { get; set; }
    public Plans Plan { get; set; }
    public string StripePublishableKey { get; set; }
    public string StripeToken { get; set; }
}

每个用户都有一个PlanId。所以我想要完成的事情是这样的:

SELECT * FROM Plans WHERE Id = (SELECT PlanId FROM Users WHERE UserId = CurrentUsersId);

到目前为止,我的控制器是

[Authorize]
public ActionResult Subscribe()
{
    string CurrentUser = User.Identity.GetUserId();
    SubscribeViewModel model = new SubscribeViewModel()
    {

        User = UserManager.FindById(CurrentUser),

        Plan = db.Plans.Where(a => a.Id == (db.Users.Where(b => b.Id == CurrentUser).Select(PlanId))
    };

    return View(model);
}

我停留在计划查询的后半部分,不确定如何仅选择当前用户的PlanId。

1 个答案:

答案 0 :(得分:1)

如您所说 每个用户都有一个PlanId。 因此,您可以执行以下操作:

[Authorize]
public ActionResult Subscribe()
{
    string currentUserId = User.Identity.GetUserId();
    var currentUser = UserManager.FindById(currentUserId),

    var  plan = db.Plans.Where(a => a.Id == currentUser.PlanId).FirstOrDefault();

    SubscribeViewModel model = new SubscribeViewModel()
    {
         User = currentUser,
         Plan = plan,
         StripePublishableKey = "StripePublishableKey",
         StripeToken = "StripeToken"
    };

    return View(model);
}