Ссылка на объект не устанавливается на экземпляр объекта. Развертывать
У меня нет никаких реальных идей о том, что вызывает эту ошибку, все работает локально. Но как только я разворачиваю приложение, я получаю ошибку.
Цитата:Ссылка на объект не устанавливается на экземпляр объекта.
Описание: необработанное исключение возникло во время выполнения текущего веб-запроса. Пожалуйста, просмотрите трассировку стека для получения дополнительной информации об ошибке и о том, где она возникла в коде.
Сведения об исключении: System.NullReferenceException: ссылка на объект не установлена на экземпляр объекта.
Ошибка Источника: Необработанное исключение было сгенерировано во время выполнения текущего веб-запроса. Информацию о происхождении и местоположении исключения можно определить с помощью приведенной ниже трассировки стека исключений.
трассировка стека:
[NullReferenceException: ссылка на объект не установлена на экземпляр объекта.]
Модель 1 SingleBid.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace TRPPortal.Models { //[Table("People", Schema = "ppl")] public class SingleBid { [Display(Name = "Single Bid No")] [Key] public int SingleBidId { get; set; } [Display(Name = "Description")] [MaxLength(100)] [Required(ErrorMessage = "Please Enter Description")] public string Description { get; set; } [Display(Name = "Company Name")] [MaxLength(100)] [Required] public string CompanyName { get; set; } [Display(Name = "Total Value")] [DataType(DataType.Currency)] [Required] public double TotalValue { get; set; } [Display(Name = "Originator")] public int OriginatorId { get; set; } [Display(Name = "Single Bid Created Date")] [Column(TypeName = "DateTime2")] public DateTime CreatedDate { get; set; } [Display(Name = "Background Information (Requester)")] [DataType(DataType.MultilineText)] [Required] public string BackgroundInformation { get; set; } [Display(Name = "Single Bid Motivation (Requester)")] [DataType(DataType.MultilineText)] [Required] public string Motivation { get; set; } [Display(Name = "Technical Recommedation (Requester)")] [DataType(DataType.MultilineText)] [Required] public string TechnicalRecommedation { get; set; } [Display(Name = "Tender Process (Commercial department)")] [DataType(DataType.MultilineText)] [Required] public string TenderProcess { get; set; } [Display(Name = "Conclusion (Requester)")] [DataType(DataType.MultilineText)] [Required] public string Conclusion { get; set; } [Display(Name = "HOD")] public int ApproverLevel1Id { get; set; } [Display(Name = "HOD Comments")] [DataType(DataType.MultilineText)] public string ApproverLevel1Comments { get; set; } [Display(Name = "Functional Leader")] public int ApproverLevel2Id { get; set; } [Display(Name = "Functional Leader Comments")] [DataType(DataType.MultilineText)] public string ApproverLevel2Comments { get; set; } [Display(Name = "Comments Chief Buyer")] [DataType(DataType.MultilineText)] public string ApproverCBComments { get; set; } [Display(Name = "Comments Contracts Coordinator")] [DataType(DataType.MultilineText)] public string ApproverCCComments { get; set; } [Display(Name = "Comments Material Controll Manager")] [DataType(DataType.MultilineText)] public string ApproverMGMComments { get; set; } [Display(Name = "Comments Engineering Leader")] [DataType(DataType.MultilineText)] public string ApproverELComments { get; set; } [Display(Name = "Comments Technical Service Leader")] [DataType(DataType.MultilineText)] public string ApproverTSLComments { get; set; } [Display(Name = "Comments Tender Committee Chairman")] [DataType(DataType.MultilineText)] public string ApproverTCTComments { get; set; } [Display(Name = "Comments Financial Leader")] [DataType(DataType.MultilineText)] public string ApproverFLComments { get; set; } public Status ApprovalStatus { get; set; } public string Assigee { get; set; } public string Status { get; set; } public int LastStatus { get; set; } public int NextStatus { get; set; } [Display(Name = "User Last Updated")] public string UserUpdated { get; set; } [Display(Name = "DateTime Last Updated")] [Column(TypeName = "DateTime2")] public DateTime DateTimeUpdated { get; set; } public virtual ICollection<SingleBidFiles> SingleBidFiles { get; set; } } public enum Status { Approve, Decline } }
Модель 2 SingleBidFiles.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace TRPPortal.Models { public class SingleBidFiles { public Guid Id { get; set; } [MaxLength(250)] public string FileName { get; set; } [MaxLength(250)] public string Extension { get; set; } public byte[] ImageByte { get; set; } public int SingleBidId { get; set; } public virtual SingleBid SingleBid { get; set; } } }
Контроллер Редактирования
> [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "SingleBidId,Description,CompanyName,TotalValue,OriginatorId,CreatedDate,BackgroundInformation,Motivation,TechnicalRecommedation,TenderProcess,Conclusion,ApproverLevel1Id,ApproverLevel1Comments,ApproverLevel2Id,ApproverLevel2Comments,ApproverCBComments,ApproverCCComments,ApproverMGMComments,ApproverELComments,ApproverTSLComments,ApproverTCTComments,ApproverFLComments,ApprovalStatus,Assigee,Status,LastStatus,NextStatus,UserUpdated,DateTimeUpdated")] SingleBid singleBid) { if (!ModelState.IsValid) { var message = string.Join(" | ", ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage)); //Log This exception to ELMAH: Exception exception = new Exception(message.ToString()); Elmah.ErrorSignal.FromCurrentContext().Raise(exception); //Return Status Code: return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message); } if (ModelState.IsValid) { if (singleBid == null) { return HttpNotFound(); } #region File Management try { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; byte[] imagebyte = null; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); BinaryReader reader = new BinaryReader(file.InputStream); imagebyte = reader.ReadBytes(file.ContentLength); SingleBidFiles singleBidFile = new SingleBidFiles() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid(), ImageByte = imagebyte, SingleBidId = singleBid.SingleBidId }; // var path = Path.Combine(Server.MapPath("/UploadImage/"), singleBidFile.Id + singleBidFile.Extension); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, singleBidFile.Id + singleBidFile.Extension); file.SaveAs(path); db.Entry(singleBidFile).State = EntityState.Added; } } } catch (Exception ex) { using (StreamWriter writer = new StreamWriter("C:\\log.txt", true)) { writer.WriteLine(ex); } } #endregion #region Current user strName string strName; strName = ADHelpder.AccountId(Request.ServerVariables["AUTH_USER"]); #endregion #region Get CurrentUser Details Users currentUser = db.Users.SingleOrDefault(user => user.AccountId == strName); #endregion #region Get Originator Details Users originator = db.Users.SingleOrDefault(user => user.UsersId == singleBid.OriginatorId); if (originator == null) { return HttpNotFound(); } #endregion #region Workflow try { // HOD - [ApproverLevel1Id] --> Functional Leader - [ApproverLevel2Id] if (singleBid.LastStatus == 0 || singleBid.NextStatus == 10) { #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == singleBid.ApproverLevel2Id); #endregion singleBid.LastStatus = 10; singleBid.NextStatus = 20; singleBid.Status = "Approval " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; sbStatus = "Approval " + assignee.DisplayName; } // Functional Leader --> ApproverLevel2Id] - Chief Buyer else if (singleBid.LastStatus == 10 && singleBid.NextStatus == 20) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["ChiefBuyer"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); #endregion singleBid.LastStatus = 20; singleBid.NextStatus = 30; singleBid.Status = "Approval " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } // Chief Buyer --> Contracts Coordinator else if (singleBid.LastStatus == 20 && singleBid.NextStatus == 30) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["ContractsCoordinator"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 110 UsersId for Michael M. Smith FROM [dbo].[Users] #endregion singleBid.LastStatus = 30; singleBid.NextStatus = 40; singleBid.Status = "Approval " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } // Contracts Coordinator --> Material Control Manager else if (singleBid.LastStatus == 30 && singleBid.NextStatus == 40) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["MaterialControlManager"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 84 UsersId for Percy S. Cawood FROM [dbo].[Users] #endregion singleBid.LastStatus = 40; singleBid.NextStatus = 50; singleBid.Status = "Approval " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } // Material Control Manager --> else if (singleBid.LastStatus == 40 && singleBid.NextStatus == 50) { //Material Control Manager -- > Autorized < 150 000 if (singleBid.TotalValue <= 149999.99) // { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["MaterialControlManager"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 84 UsersId for Percy S. Cawood FROM [dbo].[Users] #endregion singleBid.LastStatus = 50; singleBid.NextStatus = 100; singleBid.Status = "Approved " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } //Material Control Manager -- > Financial Leader Autorized < 1 000 000 else if (singleBid.TotalValue >= 149999.99 && singleBid.TotalValue < 999999.99) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["FinancialLeader"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 60 UsersId for morne.vanesch@trp.co.za FROM [dbo].[Users] #endregion singleBid.LastStatus = 50; singleBid.NextStatus = 90; singleBid.Status = "Approval to " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } //Material Control Manager -- > Engineering Leader else { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["EngineeringLeader"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 113 UsersId for Andre A. Heydenrych FROM [dbo].[Users] #endregion singleBid.LastStatus = 50; singleBid.NextStatus = 60; singleBid.Status = "Approval to " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } } // Engineering Leader --> Technical Services Leader else if (singleBid.LastStatus == 50 && singleBid.NextStatus == 60) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["TechnicalServicesLeader"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 48 UsersId for Mike M. Cowell FROM [dbo].[Users] #endregion singleBid.LastStatus = 60; singleBid.NextStatus = 70; singleBid.Status = "Approval to " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } // Technical Services Leader --> Tender Committee Chairman else if (singleBid.LastStatus == 60 && singleBid.NextStatus == 70) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["TenderCommitteeChairman"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == assigneeId); // 89 UsersId for Francois F. Vermeulen FROM [dbo].[Users] #endregion singleBid.LastStatus = 70; singleBid.NextStatus = 80; singleBid.Status = "Approval to " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } // Tender Committee Chairman --> Financial Leader else if (singleBid.LastStatus == 70 && singleBid.NextStatus == 80) { int assigneeId = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["FinancialLeader"].Value); #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == 17); // 60 UsersId for morne.vanesch@trp.co.za FROM [dbo].[Users] #endregion singleBid.LastStatus = 80; singleBid.NextStatus = 90; singleBid.Status = "Approval to " + assignee.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = assignee.AccountId; sbAssigneeDisplayName = assignee.DisplayName; sbAssigneeEmail = assignee.EmailAddress; } //Financial Leader else if (singleBid.LastStatus == 80 && singleBid.NextStatus == 90) { #region Get Assignee Details Users assignee = db.Users.SingleOrDefault(user => user.UsersId == singleBid.OriginatorId); // 60 UsersId for morne.vanesch@trp.co.za FROM [dbo].[Users] #endregion sbLastStatus = 90; sbNextStatus = 100; singleBid.Status = "Approved by Financial Leader " + currentUser.DisplayName; singleBid.Assigee = assignee.AccountId; sbAssigneeAdUser = currentUser.AccountId; sbAssigneeDisplayName = currentUser.DisplayName; sbAssigneeEmail = currentUser.EmailAddress; sbStatus = "Approved by Financial Leader " + currentUser.DisplayName; } } catch (Exception ex) { throw ex.InnerException; } #endregion #region Check Approval Status try { if (!singleBid.ApprovalStatus.Equals("Approve")) { string linkurl = (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["Sitelink"].Value); string Body; Body = "<p> SingleBid Approval - New </p> </br> "; Body = Body + "<p>Please review the folowing Single Bid<br/>"; Body = Body + "</p><p>Requested By: " + originator.DisplayName; Body = Body + "</p><p>Created Date: " + singleBid.CreatedDate; Body = Body + "</p><p>Description : " + singleBid.Description; Body = Body + "</p><p>Motivation: " + singleBid.Motivation; Body = Body + "</p><p>Status: " + singleBid.Status; Body = Body + "</p><br><p>Please review:</p>"; Body = Body + "<p><a href=" + linkurl + singleBid.SingleBidId + "> Single Bid: " + singleBid.SingleBidId + "</a>"; EmailHelper.SendEmail(sbAssigneeEmail, originator.EmailAddress, "SingleBid Approval - " + singleBid.SingleBidId, Body, true); } else { string linkurl = (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["Sitelink"].Value); singleBid.LastStatus = singleBid.LastStatus - 10; ; singleBid.NextStatus = 99; singleBid.Status = "Decline -" + currentUser.DisplayName; string Body; Body = "<p> SingleBid Approval - New </p> </br> "; Body = Body + "<p>Please note the folowing Single Bid<br/>"; Body = Body + "</p><p>Requested By: " + originator.DisplayName; Body = Body + "</p><p>Created Date: " + singleBid.CreatedDate; Body = Body + "</p><p>Description : " + singleBid.Description; Body = Body + "</p><p>Motivation: " + singleBid.Motivation; Body = Body + "</p><p>Status: " + singleBid.Status; Body = Body + "</p><p>Declined by: " + currentUser.DisplayName; Body = Body + "</p><br><p>Has been Declined. To review:</p>"; Body = Body + "< p >< a href = " + linkurl + +singleBid.SingleBidId + " > Single Bid: " + singleBid.SingleBidId + "</a>"; EmailHelper.SendEmail(originator.EmailAddress, "chrisv@trp.co.za", "SingleBid Approval - " + singleBid.SingleBidId, Body, true); } } catch (Exception ex) { throw ex.InnerException; } #endregion #region Commit SingleBid to db /* try { singleBid.DateTimeUpdated = DateTime.Now; singleBid.UserUpdated = strName; singleBid.Assigee = sbAssigneeAdUser; db.Entry(singleBid).State = EntityState.Modified; db.SaveChanges(); } catch (Exception ex) { throw ex.InnerException; } */ #endregion #region Update Approval db /* string link = (System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/SingleBidArea/Web.config").AppSettings.Settings["Sitelink"].Value); var Link = link + singleBid.SingleBidId; Approval approval = db.Approval.SingleOrDefault(appr => appr.FormId == singleBid.SingleBidId && appr.Form == "SingleBids"); // Approval approval = db.Approval.Find(singleBid.SingleBidId); if (approval == null) { try { List<Approval> newapproval = new List<Approval>(); Approval app = new Approval(); thisForm = "SingleBids"; app.Form = thisForm.ToString(); app.FormId = singleBid.SingleBidId; app.Description = singleBid.Description; app.Link = Link; app.Actionee = sbAssigneeDisplayName; app.ActioneeEmail = sbAssigneeEmail; app.ActioneeAdUser = sbAssigneeAdUser; app.ApprovalDateTime = DateTime.Now; app.UserUpdated = singleBid.UserUpdated; app.DateTimeUpdated = DateTime.Now; db.Approval.Add(app); db.SaveChanges(); } catch (Exception ex) { throw ex; } } else { try { db.Approval.Remove(approval); List<Approval> newapproval = new List<Approval>(); Approval app = new Approval(); thisForm = "SingleBids"; app.Form = thisForm.ToString(); app.FormId = singleBid.SingleBidId; app.Description = singleBid.Description; app.Link = Link; app.Actionee = sbAssigneeDisplayName; app.ActioneeEmail = sbAssigneeEmail; app.ActioneeAdUser = sbAssigneeAdUser; app.ApprovalDateTime = DateTime.Now; app.UserUpdated = singleBid.UserUpdated; app.DateTimeUpdated = DateTime.Now; db.Approval.Add(app); db.SaveChanges(); } catch (Exception ex) { throw ex; } } */ #endregion return RedirectToAction("Index"); } return View(singleBid); }
Что я уже пробовал:
У меня нет никаких реальных идей о том, что вызывает эту ошибку, все работает локально. Но как только я разворачиваю приложение, я получаю ошибку.