public ActionResult Conversations() { var iam=db.Users.Where(u=>u.Login==User.Identity.Name).FirstOrDefault(); User friend; Message msg; var conversations = db.Conversations.Where(con => con.UserOne == iam.Id || con.UserTwo == iam.Id); List<ConversationViewModel> model = new List<ConversationViewModel>(); foreach (var item in conversations) { using (DatabaseContext db1 = new DatabaseContext()) { msg = db1.Messages.Where(m => m.ConversationId == item.Id).ToList().LastOrDefault(); if (msg == null) { msg = new Message() { Text = " " }; } if (iam.Id == item.UserOne) { friend = db1.Users.Include("Profile").Where(u => u.Id == item.UserTwo).FirstOrDefault(); } else { friend = db1.Users.Include("Profile").Where(u => u.Id == item.UserOne).FirstOrDefault(); } model.Add(new ConversationViewModel() { Id=item.Id, Iam = iam, Friend = friend, Messages = new List<Message>() { msg } }); } } return View(model); }
public ActionResult Send(Message model,int? idConversation,string returnUrl) { if (ModelState.IsValid) { var iam = db.Users.Where(u => u.Login == User.Identity.Name).FirstOrDefault(); db.Messages.Add(new Message() { Text = model.Text, Time = DateTime.Now, UserId = iam.Id, Ip = Request.UserHostAddress, ConversationId = (int)idConversation }); db.SaveChanges(); return Redirect(returnUrl); } else { return View(model); } }