转换为自定义类型失败

时间:2014-10-24 06:45:47

标签: c# linq casting

我正在维护由其他人创建的程序(argh)。从LINQ查询填充自定义类时,以下语句会产生Specified cast is not valid的错误 但是对于ContactPersons视图中的所有记录都没有这样做,只是对某些记录 - 即使记录看起来与我相同。

如何确定演员表失败的原因?

var smDataContext = new SurveyManagerDataClassesDataContext(dbConnectionString);

ContactPerson contactPerson =
    (from contactPersons in smDataContext.ContactPersons
     where (contactPersons.ContactPersonID.Trim().ToUpper()
            == this.ContactPersonID.Trim().ToUpper())
     select contactPersons)
    .FirstOrDefault<ContactPerson>();

该课程如下:

public partial class ContactPerson
{
    private string _ContactPersonID;
    private string _Surname;
    private string _FirstName;
    private string _EMail;
    private string _CompanyID;
    private System.Nullable<bool> _IsDefaultForAdhocSurvey;
    private System.Nullable<bool> _IsDefaultForClosingOfTasksSurvey;
    private System.Nullable<bool> _IsDefaultForScheduledProjectSurvey;
    private System.Nullable<bool> _IsDefaultForScheduledContractSurvey;

    public ContactPerson()
    {
    }
    ...

示例数据: 这些数据从直接从多个表中读取数据的视图中复制和粘贴:

ContactPersonID Surname FirstName   EMail               CompanyID   IsDefaultForAdhocSurvey IsDefaultForClosingOfTasksSurvey    IsDefaultForScheduledProjectSurvey  IsDefaultForScheduledContractSurvey
Patrick Grey    Grey    Patrick     patrick@grey.co.za  2410955     0   0   1   0
Patrick Black   Black   Patrick     patrick@black.co.za 2410955     0   0   1   0

这样做不起作用:

CREATE VIEW [dbo].[ContactPersonsView]
AS
SELECT
    'Patrick Grey' as ContactPersonID,
    'Grey' as Surname,
    'Patrick' As FirstName,
    'patrick@grey.co.za' AS Email,
    '1234' as CompanyID,
    0 as IsDefaultForAdhocSurvey,
    0 as IsDefaultForClosingOfTasksSurvey,
    1 as IsDefaultForScheduledProjectSurvey,
    0 as IsDefaultForScheduledContractSurvey

1 个答案:

答案 0 :(得分:1)

感谢您的所有评论。我应该将我的布尔值转换为位。

因此,如果我改变我的观点:

CREATE VIEW [dbo].[ContactPersonsView]
AS

    SELECT 'Patrick Grey' as ContactPersonID, 'Grey' as Surname, 'Patrick' As FirstName, 'patrick@grey.co.za' AS Email, '1234' as CompanyID,
    0 as IsDefaultForAdhocSurvey, 0 as IsDefaultForClosingOfTasksSurvey, 1 as IsDefaultForScheduledProjectSurvey, 0 as IsDefaultForScheduledContractSurvey

到此:

SELECT 'Patrick Grey' as ContactPersonID, 'Grey' as Surname, 'Patrick' As FirstName, 'patrick@grey.co.za' AS Email, '1234' as CompanyID,
CONVERT(bit, 0) as IsDefaultForAdhocSurvey, CONVERT(bit, 0) as IsDefaultForClosingOfTasksSurvey, CONVERT(bit, 1) as IsDefaultForScheduledProjectSurvey, CONVERT(bit, 0) as IsDefaultForScheduledContractSurvey

然后它有效。