// How to create a db instance // PostContext db = new PostContext(); // db.Posts is how to access the db of posts. // Example how to get posts by usr // var postsSortedByUser = dataContext.Posts.Where(s => s.UserName == User.Identity.Name); public ActionResult Index() { var dataContext = new PostContext(); var posts = dataContext.Posts.OrderByDescending(s => s.CreatedAt).ToList(); return View(posts); }
public ActionResult Profile(Post post) { /** * Save the post to the database * Post save requires User Name and Time Created at (datetime.now) **/ String myUserName = User.Identity.GetUserName(); post.UserName = myUserName; post.CreatedAt = DateTime.Now; var dataContext = new PostContext(); dataContext.Posts.Add(post); dataContext.SaveChanges(); return RedirectToAction("Profile"); }
public ActionResult Profile() { // Can look at how the Index action was handled in HomeController for example /** * Use linq/sql here to create a list of Posts that has only posts by this user and passes it to the view * * var posts = new PostContext(); * * var postlist = posts.Posts.OrderByDescending(s => s.CreatedAt).ToList(); * * return View( postlist ); * **/ // This is directly copied from HomeController#Index so that I can do view without error // This is not fully done and still needs filtered by the current user var dataContext = new PostContext(); //var posts = dataContext.Posts.OrderByDescending(s => s.CreatedAt).ToList(); //var posts = dataContext.Posts.OrderByDescending(s => s.UserName).ToList(); //var posts = dataContext.Posts.Find(User.Identity.GetUserName()). //var posts = dataContext.Posts.Find(User.Identity.GetUserId()); //I messed with this for a long time and I can't for the life of me figure out how to have the data context return only the posts from one specific user. I could do it in SQL but I am not sure how to run SQL commands and get proper returned values. /** This won't work because it alters the item being iterated over, throwing an exception foreach(var Post in posts) { if(Post.UserName != User.Identity.GetUserName()) { posts.Remove(Post); } } **/ /** var posts2 = from u in dataContext.Posts where u.UserName.Equals(User.Identity.GetUserName()) select u; **/ String myUserName = User.Identity.GetUserName(); var posts3 = dataContext.Posts.Where(u => u.UserName == myUserName).ToList(); //var posts3 = dataContext.Posts.Where(u => u.UserName == "Angela Bohan").ToList(); return View(posts3); }