Question

I'm trying to get the userid of the currently logged in user. Here is my code:

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

        }
    }

I'm calling the method from my controller using this:

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);

   }

The error is showing as "input string is not in correct format". Please help. Thanks.

Était-ce utile?

La solution

Your query returns an IEnumerable. You need to get only the single record:

using (var context = new TourBlogEntities1())
{
    var userIds = from s in context.UserInfoes
                 where s.UserName == _UserName
                 select s.UserID;
    return userIds.Single();
}

By the way the .Single() method will throw an exception if there are more than 1 records matching the criteria. Hopefully you have an unique constraint on the Username field inside your database.

Autres conseils

 CreatedBy = this.HttpContext.User.Identity.Name,
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top