2

我有一个应用程序开始偶尔抛出“指定的强制转换无效”异常。我无法始终如一地重现此错误,这让我和我的用户发疯。

违规代码:

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]
4

2 回答 2

3

我有同样的错误,问题也间歇性地发生。

原因是数据库中的列类型与 .dbml 文件中的字段类型之间的类型不匹配

因此,也许检查自动生成的 linq2sql 类中的类型(即 cts_complaints,而不是我假设您自己编写的模型类 Complaint)与数据库中的类型匹配。

(针对我的具体情况的详细信息:在 linq2sql .dbml 文件中有一个类型为 double 的字段,但在数据库中,该列是 datetime - 不知道这是如何发生的 - 可能最初 DB 列和 .dbml 字段具有相同的类型,然后有人在不重新生成 .dbml 文件的情况下更改了数据库中的类型)。

于 2012-08-23T08:30:15.530 回答
1

错误: Cast 无效(尝试使用 LINQ 从实体将数据加载到数据网格中时)

原因:映射实体和 SQL Server 表中的数据类型不同。

示例:在我的情况下,我在 Entity 类中使​​用了一个 int,在 DB 中使用了一个 bigint,这就是我收到错误的原因。

于 2012-10-18T04:44:38.880 回答