2016-07-31 56 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!