我正在尝试获取当前登录用户的用户ID。这是我的代码:
public int GetUserID(string _UserName)
{
using (var context = new TourBlogEntities1())
{
var UserID = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return Int32.Parse(UserID.ToString()); //error is showing here
}
}
我正在使用此控制器从我的控制器调用该方法:
public ActionResult NewPost(NewPost model)
{
var Business = new Business();
var entity = new Post();
entity.PostTitle = model.PostTitle;
entity.PostStory = model.PostStory;
entity.UserID = Business.GetUserID(User.Identity.Name);
Business.NewPost(entity);
Business.ViewPost(entity);
return View("ViewPost", model);
}
错误显示为“输入字符串格式不正确”。请帮忙。感谢。
答案 0 :(得分:1)
您的查询返回IEnumerable。您只需要获得单个记录:
using (var context = new TourBlogEntities1())
{
var userIds = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return userIds.Single();
}
顺便说一下,如果有超过1条符合条件的记录,.Single()
方法将抛出异常。希望您对数据库中的用户名字段有唯一约束。
答案 1 :(得分:1)
CreatedBy = this.HttpContext.User.Identity.Name,