2016-07-31 69 views
-1

这是我在通知控制器中的索引操作的代码。如何避免asp.net mvc中的System.Data.Entity.Core.EntityCommandExecutionException?

public ActionResult Index() 
     { 
      //gets the current user 
      ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 

      //checks if the user is logged in 
      bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated; 
      if (val1 == false) 
      { 
       return RedirectToAction("Login", "Account"); 
      } 
      var myNotif = db.Notifications.Where(s => s.User1_Id == currentUser.Id || s.User2_Id == currentUser.Id).Where(s => s.Active_Status != currentUser.Id); 
      ViewBag.Autobots = new NotificationStatus[myNotif.Count()]; 
      int i = 0; 
      foreach(var item in myNotif) 
      { 
       ViewBag.Autobots[i].name = db.Users.Where(x => item.Active_Status == x.Id).First().FirstName + " " + db.Users.Where(x => item.Active_Status == x.Id).First().LastName; 
       i++; 
      } 
      return View(myNotif.ToList()); 
     } 

     private class NotificationStatus 
     { 
      string name; 
     } 

我在这里得到这个错误。那么我该如何避免它?我试图发送数据来查看,因此我使用的是字符串数组。我的Linq查询是否错误? enter image description here

+1

你好,试着看看内部的例外。 –

+0

我该怎么做? –

+0

在附加的图像中,剪贴板上有一个链接复制异常详细信息。点击它,然后粘贴到文本编辑器中 –

回答

0
public ActionResult Index() 
{ 
    var userId=User.Identity.GetUserId(); 

    if(!User.Identity.IsAuthenticated) return RedirectToAction("Login", "Account"); 

    var myNotif = db.Notifications 
       .Where(s => s.User1_Id == userId || s.User2_Id == userId) 
       .Where(s => s.Active_Status != userId).ToList(); 

    ViewBag.Autobots = new NotificationStatus[myNotif.Count()]; 
    int i = 0; 
    foreach(var item in myNotif) 
    { 
     var user=db.Users.FirstOrDefault(x=>x.Id==item.Active_Status); 
     ViewBag.Autobots[i].name = user.FirstName + " " + user.LastName; 
     i++; 
    } 
    return View(myNotif.ToList()); 
} 

我只是重构你的代码,有一些细微的变化。

这应该工作,在列表不会给你那个错误。

我sugestion是创建一个视图模型,如:

public class ViewModel 
{ 
public List<Notification> Notifications {get;set;} 
public NotificationStatus[] NotificationStatusArr {get;set;} 
} 

并发送视图模型到视图,而不是ViewBags!