我有一个应用程序开始偶尔抛出“指定的强制转换无效”异常。我无法始终如一地重现此错误,这让我和我的用户发疯。
违规代码:
public Complaint GetComplaintById(int Id)
{
    Complaint complaint = (from c in _context.cts_complaints
                           join ud in _context.cts_user_details on c.CreatedBy equals ud.UserId
                           where c.Id == Id
                           select new Complaint
                           {
                              Id = c.Id,
                              CompanyId = c.CompanyId,
                              ComplaintTypeId = c.ComplaintTypeId,
                              CategoryId = c.CategoryId,
                              ReportCategoryId = c.ReportCategoryId,
                              ParentId = c.ParentId,
                              LanguageId = c.LanguageId,
                              AreaId = c.AreaId,
                              Title = c.Title,
                              Description = c.Description,
                              ResponseDue = c.ResponseDue,
                              DateReceived = c.DateReceived,
                              FPSCNumber = c.FPSCNumber,
                              FPSCRepresentative = c.FPSCRepresentative,
                              ContactMethodId = c.ContactMethodId,
                              ContactedBy = c.ContactedBy,
                              CreatedDate = c.CreatedDate,
                              CreatedBy = c.CreatedBy,
                              CreatedByName = ud.Name,
                              Status = c.Status,
                              AttachmentsArchived = c.AttachmentsArchived,
                              Timestamp = c.Timestamp,
                            }).FirstOrDefault();
    complaint.Users = this.GetUsersByComplaintId(Id);
    return complaint;
}
堆栈跟踪:
Specified cast is not valid.
   at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
   at ComplaintTracking.Business.Data.SqlComplaintRepository.GetComplaintById(Int32 Id) in C:\SourceCode2010\ComplaintTracking\Service Pack\1.0 ComplaintTracking\ComplaintTracking.Business\Data\SqlComplaintRepository.cs:line 20
   at ComplaintTracking.Business.Managers.ComplaintManager.GetComplaintById(Int32 Id) in C:\SourceCode2010\ComplaintTracking\Service Pack\1.0 ComplaintTracking\ComplaintTracking.Business\Managers\ComplaintManager.cs:line 33
   at ComplaintTracking.Web.UserControls.ComplaintViews.ResolveViewPresenter.Init() in C:\SourceCode2010\ComplaintTracking\Service Pack\1.0 ComplaintTracking\ComplaintTracking.Web\UserControls\ComplaintViews\ResolveViewPresenter.cs:line 39
   at ComplaintTracking.Web.Library.BaseUserControl`2.OnLoad(EventArgs e) in C:\SourceCode2010\ComplaintTracking\Service Pack\1.0 ComplaintTracking\ComplaintTracking.Web\Library\BaseUserControl.cs:line 56
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
更新: 我正在尝试使用存储库模式。我有一个名为 cts_complaints 的 LINQ 2 SQL ORM 对象,它是我的 SQL Server 表 dbo.cts_complaints 的 1-1 映射。在我的应用程序中,我有一个名为 Complaint 的模型。我的存储库是从 cts_complaints 映射到 Complaint。
[HasSelfValidation]
public class Complaint
{
    public Complaint()
    {
    CreatedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name;
    CreatedDate = DateTime.Now;
    DateReceived = DateTime.Now;
    Users = new List<ComplaintUser>();
    }
    public int Id { get; internal set; }
    public int CompanyId { get; set; }
    public int ComplaintTypeId { get; set; }
    public int CategoryId { get; set; }
    public int ReportCategoryId { get; internal set; }
    public int? ParentId { get; set; }
    public int LanguageId { get; set; }
    public int? AreaId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime ResponseDue { get; set; }
    public DateTime DateReceived { get; set; }
    public string FPSCNumber { get; set; }
    public string FPSCRepresentative { get; set; }
    public int ContactMethodId { get; set; }
    public string ContactedBy { get; set; }
    public int Status { get; set; }
    public bool AttachmentsArchived { get; set; }
    public DateTime CreatedDate { get; internal set; }
    public string CreatedBy { get; internal set; }
    public string CreatedByName { get; set; }       
    public byte[] Timestamp { get; internal set; }
    public List<ComplaintUser> Users { get; internal set; }
    [SelfValidation()]
    public void ValidateUsers(ValidationResults results)
    {
    //if id is 0 it's new.  There must be user
    if (Users.Count==0)
            results.AddResult(new ValidationResult("You must assign at least one user.", this, "Users", "", null));
    }
}
cts_complaints:
CREATE TABLE [dbo].[cts_complaint](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [CompanyId] [int] NOT NULL,
    [ComplaintTypeId] [int] NOT NULL,
    [CategoryId] [int] NOT NULL,
    [ReportCategoryId] [int] NOT NULL,
    [ParentId] [int] NULL,
    [LanguageId] [int] NOT NULL,
    [AreaId] [int] NULL,
    [Title] [nvarchar](50) NOT NULL,
    [Description] [nvarchar](max) NOT NULL,
    [ResponseDue] [datetime] NOT NULL,
    [DateReceived] [datetime] NOT NULL,
    [FPSCNumber] [nvarchar](50) NOT NULL,
    [FPSCRepresentative] [nvarchar](50) NOT NULL,
    [ContactMethodId] [int] NOT NULL,
    [ContactedBy] [nvarchar](50) NOT NULL,
    [CreatedDate] [datetime] NOT NULL,
    [CreatedBy] [nvarchar](50) NOT NULL,
    [Status] [int] NOT NULL,
    [AttachmentsArchived] [bit] NOT NULL,
    [Timestamp] [timestamp] NOT NULL,
 CONSTRAINT [PK_cts_complaint] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
cts_user_details:
CREATE TABLE [dbo].[cts_user_detail](
    [UserId] [nvarchar](50) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Email] [nvarchar](255) NOT NULL,
    [ManagerEmail] [nvarchar](255) NOT NULL,
    [Role] [nvarchar](15) NOT NULL,
    [Timestamp] [timestamp] NOT NULL,
 CONSTRAINT [PK_cts_user_detail_1] PRIMARY KEY CLUSTERED 
(
    [UserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]