MVC获取属于当前用户的内容

时间:2018-10-01 17:57:43

标签: asp.net-mvc

我正在使用ASP.net Identity,并具有一个其中包含UserID的模型:

 public class Response
    {
        public int Id { get; set; }
        public virtual Survey Survey { get; set; }
        public string Userid { get; set; }
        public int Ftes { get; set; }
        public int Members { get; set; }
        public decimal Assets { get; set; }
        public decimal Budget { get; set; }
        public string Govbody { get; set; }
}

以及其中包含responseid的表:

public class Basiclife
{
    [Key]
    public int Id { get; set; }
    public int ResponseId { get; set; }
    public string Plantype { get; set; }
    public int Enrolledftes { get; set; }
    public decimal Pctemployer { get; set; }
    public decimal Fixedbenamt { get; set; }
    public decimal Salarymult { get; set; }
    public decimal Bencap { get; set; }
}

我正在尝试添加Basiclife记录并将ID设置为等于当前登录用户的responseId(每个用户将只有一个Response):

 [HttpPost]
        public ActionResult CreateBasicLifeResponse(IEnumerable<BasicLifeResponseViewModel> response)
        {
            string currentUserId = User.Identity.GetUserId();
            Response response = db.response.FirstOrDefault(x => x.Userid = currentUserId);
            int responseid = response.Id;


            foreach(var y in response)
            {
                Basiclife blr = new Basiclife();
                blr.ResponseId = responseid;
                /*
                 * the rest of the required BasicLife fields
                 * */

            }

            return View();
        }

我收到错误消息“无法在行Response response = db.response.FirstOrDefault(x => x.Userid = currentUserId);上将类型字符串隐式转换为bool

鉴于所有用户ID都是字符串,所以我不确定为什么要尝试将其转换为bool。

2 个答案:

答案 0 :(得分:1)

您缺少等号:

Response response = db.response.FirstOrDefault(x => x.Userid == currentUserId);

答案 1 :(得分:0)

您忘记放置均等。您应按以下方式使用它。

错误(您使用的)=> db.response.FirstOrDefault(x => x.Userid == currentUserId);

正确(应为)=> db.response.FirstOrDefault(x => x.Userid == currentUserId);

FirstOrDefault仅获取布尔值。

相关问题