473,289 Members | 1,875 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

LINQ Issue - "Specified cast is not valid"

I'm attempting to use LINQ to insert a record into a child table and I'm
receiving a "Specified cast is not valid" error that has something to do w/
the keys involved. The stack trace is:

======================
Message: Specified cast is not valid.

Type: System.InvalidCastException
Source: System.Data.Linq
TargetSite: Boolean TryCreateKeyFromValues(System.Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Linq.IdentityManager.StandardIdentityM anager.SingleKeyManager`2.TryCreateKeyFromValues(O bject[] values, V& v)
at
System.Data.Linq.IdentityManager.StandardIdentityM anager.IdentityCache`2.Find(Object[] keyValues)
at System.Data.Linq.IdentityManager.StandardIdentityM anager.Find(MetaType
type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObjec t(MetaType type,
Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(Meta Association assoc,
Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(Con flictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(Conflic tMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()

(.....)

======================

This error is being thrown on the following code:
============
ResponseDataContext db = new ResponseDataContext(m_ConnectionString);
CodebookVersion codebookVersion = db.CodebookVersions.Single(cv =>
cv.VersionTag == m_CodebookVersionTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionName = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion.ResponseCodes.Add(rc);
db.SubmitChanges(); //exception gets thrown here
============

The tables in question have a FK relationship between the two of them.
The parent table's column is called 'id', is the PK, and is of type: INT
NOT NULL IDENTITY
The child table's column is called 'responseCodeTableId' and is of type: INT
NOT NULL

codebookVersion (parent class) maps to table tblResponseCodeTable
responseCode (childClass) maps to table tblResponseCode

If I execute SQL directly, it works. e.g.
INSERT INTO tblResponseCode
(responseCodeTableId, surveyQuestionName, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
Updates to the same class work properly. e.g.
codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah";
db.SubmitChanges(); //no exception - change is committed to db

I've examined the variable, rc, after the .Add() operation and it does,
indeed, receive the proper responseCodeTableId, just as I would expect since
I'm adding it to that collection.

tblResponseCodeTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTableId int
surveyQuestionName nvarchar
code smallint
description nvarchar
dtCreate smalldatetime

dtCreate has a default value of GetDate().
The only other bit of useful information that I can think of is that no SQL
is ever tried against the database, so LINQ is blowing up before it ever
tries (hence the error not being a SqlException). I've profiled and verified
that no attempt is made to execute any statements on the database.
Can anyone shed any light on this situation for me? What incredibly obvious
thing am I missing here?

--
-Paul Prewett
Oct 26 '08 #1
3 12382
Hi Paul,

From the issue description, I understand you're encounering some exception
when try inserting a main table record via a foreignkey associated table,
correct?

As you said that the direct T-SQL inserting approach work, have you tried
using the DataContext.Log to output the LINQ translated T-SQL code to see
whehter it matches the working SQL code?

#DataContext.Log - Logging LINQ To SQL Output to Console or Debugger Output
Window
http://www.davidhayden.com/blog/dave...ntextLogLoggin
gLINQToSQLOutputConsoleDebuggerOuputWindow.aspx

Also, if possible, you can provide a simlified version of the two tables
and code(the DDL or table schema). I'd like to perform some tests on my
side.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/...tance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
>From: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= <li***@community.nospam>
Subject: LINQ Issue - "Specified cast is not valid"
Date: Sat, 25 Oct 2008 17:41:01 -0700
>
I'm attempting to use LINQ to insert a record into a child table and I'm
receiving a "Specified cast is not valid" error that has something to do
w/
>the keys involved. The stack trace is:

======================
Message: Specified cast is not valid.

Type: System.InvalidCastException
Source: System.Data.Linq
TargetSite: Boolean TryCreateKeyFromValues(System.Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Linq.IdentityManager.StandardIdentityM anager.SingleKeyManager`2.
TryCreateKeyFromValues(Object[] values, V& v)
at
System.Data.Linq.IdentityManager.StandardIdentityM anager.IdentityCache`2.Fin
d(Object[] keyValues)
at
System.Data.Linq.IdentityManager.StandardIdentityM anager.Find(MetaType
>type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObjec t(MetaType type,
Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(Meta Association assoc,
Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(Con flictMode
failureMode)
at System.Data.Linq.DataContext.SubmitChanges(Conflic tMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()

(.....)

======================

This error is being thrown on the following code:
============
ResponseDataContext db = new
ResponseDataContext(m_ConnectionString);
CodebookVersion codebookVersion = db.CodebookVersions.Single(cv
=>
>cv.VersionTag == m_CodebookVersionTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionName = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion.ResponseCodes.Add(rc);
db.SubmitChanges(); //exception gets thrown here
============

The tables in question have a FK relationship between the two of them.
The parent table's column is called 'id', is the PK, and is of type: INT
NOT NULL IDENTITY
The child table's column is called 'responseCodeTableId' and is of type:
INT
>NOT NULL

codebookVersion (parent class) maps to table tblResponseCodeTable
responseCode (childClass) maps to table tblResponseCode

If I execute SQL directly, it works. e.g.
INSERT INTO tblResponseCode
(responseCodeTableId, surveyQuestionName, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
Updates to the same class work properly. e.g.
codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah";
db.SubmitChanges(); //no exception - change is committed to db

I've examined the variable, rc, after the .Add() operation and it does,
indeed, receive the proper responseCodeTableId, just as I would expect
since
>I'm adding it to that collection.

tblResponseCodeTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTableId int
surveyQuestionName nvarchar
code smallint
description nvarchar
dtCreate smalldatetime

dtC
Oct 27 '08 #2
Hi Steven -

Thanks for taking a look at this.

The first table schema is listed in my original post.

tblResponseTable definition (which maps to CodebookVersion)
COLUMN_NAME TYPE_NAME
id int identity
versionTag nvarchar
responseVersionTag nvarchar
dtCreate smalldatetime

dtCreate again has a default value of GETDATE()

As for the generated T-SQL, as I see the issue, there is never any generated
T-SQL. The error is coming from LINQ before it generates the T-SQL. Would
using the DataContext Log still be instructive?
--
-Paul Prewett
""Steven Cheng"" wrote:
Hi Paul,

From the issue description, I understand you're encounering some exception
when try inserting a main table record via a foreignkey associated table,
correct?

As you said that the direct T-SQL inserting approach work, have you tried
using the DataContext.Log to output the LINQ translated T-SQL code to see
whehter it matches the working SQL code?

#DataContext.Log - Logging LINQ To SQL Output to Console or Debugger Output
Window
http://www.davidhayden.com/blog/dave...ntextLogLoggin
gLINQToSQLOutputConsoleDebuggerOuputWindow.aspx

Also, if possible, you can provide a simlified version of the two tables
and code(the DDL or table schema). I'd like to perform some tests on my
side.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/...tance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
From: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= <li***@community.nospam>
Subject: LINQ Issue - "Specified cast is not valid"
Date: Sat, 25 Oct 2008 17:41:01 -0700

I'm attempting to use LINQ to insert a record into a child table and I'm
receiving a "Specified cast is not valid" error that has something to do
w/
the keys involved. The stack trace is:

======================
Message: Specified cast is not valid.

Type: System.InvalidCastException
Source: System.Data.Linq
TargetSite: Boolean TryCreateKeyFromValues(System.Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Linq.IdentityManager.StandardIdentityM anager.SingleKeyManager`2.
TryCreateKeyFromValues(Object[] values, V& v)
at
System.Data.Linq.IdentityManager.StandardIdentityM anager.IdentityCache`2.Fin
d(Object[] keyValues)
at
System.Data.Linq.IdentityManager.StandardIdentityM anager.Find(MetaType
type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObjec t(MetaType type,
Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(Meta Association assoc,
Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(Con flictMode
failureMode)
at System.Data.Linq.DataContext.SubmitChanges(Conflic tMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()

(.....)

======================

This error is being thrown on the following code:
============
ResponseDataContext db = new
ResponseDataContext(m_ConnectionString);
CodebookVersion codebookVersion = db.CodebookVersions.Single(cv
=>
cv.VersionTag == m_CodebookVersionTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionName = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion.ResponseCodes.Add(rc);
db.SubmitChanges(); //exception gets thrown here
============

The tables in question have a FK relationship between the two of them.
The parent table's column is called 'id', is the PK, and is of type: INT
NOT NULL IDENTITY
The child table's column is called 'responseCodeTableId' and is of type:
INT
NOT NULL

codebookVersion (parent class) maps to table tblResponseCodeTable
responseCode (childClass) maps to table tblResponseCode

If I execute SQL directly, it works. e.g.
INSERT INTO tblResponseCode
(responseCodeTableId, surveyQuestionName, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
Updates to the same class work properly. e.g.
codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah";
db.SubmitChanges(); //no exception - change is committed to db

I've examined the variable, rc, after the .Add() operation and it does,
indeed, receive the proper responseCodeTableId, just as I would expect
since
I'm adding it to that collection.

tblResponseCodeTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTableId int
surveyQuestionName nvarchar
code smallint
description nvarchar
dtCreate smalldatetime

dtC

Oct 27 '08 #3
Hi Paul,

Thanks for your reply.

Yes, if the error occurs before the LINQ has generated the T-SQL, the LOG
does be of less assistance.

I have just created two tables per your schema and performed some tests. It
seems my local program can sucessfully run the code snippet below:

====================
using (ResponseDataContextDataContext ctx = new
ResponseDataContextDataContext())
{

CodebookVersion codebookVersion =
ctx.CodebookVersions.Single(
cv =>
cv.id == 2);

MessageBox.Show(codebookVersion.ToString());

ResponseCode rc = new ResponseCode()
{
surveyQuestionName= "Q11",
code = 3,
description = "Yet another code"
};
codebookVersion.ResponseCodes.Add(rc);
ctx.SubmitChanges();
================

# for the two tables, I've manually added the foreign key constraint betwee
them. Not sure whether thsi matters.

And here is the LINQ log trace I've printed on my side:

=================
SELECT [t0].[id], [t0].[versionTag], [t0].[responseVersionTag],
[t0].[dtCreate]
FROM [dbo].[tblResponseTable] AS [t0]
WHERE [t0].[id] = @p0
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [2]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build:
3.5.21022.8

INSERT INTO [dbo].[tblResponseCodeTable]([responseCodeTableId],
[surveyQuestionName], [code], [description], [dtCreate])
VALUES (@p0, @p1, @p2, @p3, @p4)

SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [2]
-- @p1: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [Q11]
-- @p2: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [3]
-- @p3: Input NVarChar (Size = 16; Prec = 0; Scale = 0) [Yet another code]
-- @p4: Input SmallDateTime (Size = 0; Prec = 0; Scale = 0) [Null]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build:
3.5.21022.8
==================

If necessary, I can send you my test project for reference.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we

can improve the support we provide to you. Please feel free to let my
manager know what you think of

the level of service provided. You can send feedback directly to my manager
at: ms****@microsoft.com.
--------------------
>From: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= <li***@community.nospam>
References: <BB**********************************@microsoft.co m>
<HQ**************@TK2MSFTNGHUB02.phx.gbl>
>Subject: RE: LINQ Issue - "Specified cast is not valid"
Date: Mon, 27 Oct 2008 02:56:00 -0700
>
Hi Steven -

Thanks for taking a look at this.

The first table schema is listed in my original post.

tblResponseTable definition (which maps to CodebookVersion)
COLUMN_NAME TYPE_NAME
id int identity
versionTag nvarchar
responseVersionTag nvarchar
dtCreate smalldatetime

dtCreate again has a default value of GETDATE()

As for the generated T-SQL, as I see the issue, there is never any
generated
>T-SQL. The error is coming from LINQ before it generates the T-SQL.
Would
>using the DataContext Log still be instructive?
--
-Paul Prewett
""Steven Cheng"" wrote:
>Hi Paul,

From the issue description, I understand you're encounering some
exception
>when try inserting a main table record via a foreignkey associated
table,
>correct?

As you said that the direct T-SQL inserting approach work, have you
tried
>using the DataContext.Log to output the LINQ translated T-SQL code to
see
>whehter it matches the working SQL code?

#DataContext.Log - Logging LINQ To SQL Output to Console or Debugger
Output
>Window
http://www.davidhayden.com/blog/dave/archive/2007/08/17/DataContextLogLoggin
>gLINQToSQLOutputConsoleDebuggerOuputWindow.aspx

Also, if possible, you can provide a simlified version of the two tables
and code(the DDL or table schema). I'd like to perform some tests on my
side.

Sincerely,

Steven Cheng
Oct 28 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Tao | last post by:
I just upgraded .NET framework to 1.1 and VS.Net to 2003 version and tried to test it out. I created an ASP.NET project using the wizard and tried to run it by hitting "F5". I got an exception:...
1
by: Ron Holmes | last post by:
I posted this question on the Crystal Reports Support site and I am still waiting for an answer. Using Crystal Reports 9.0 Developer Full edition: My Crystal report .RPT file has a Picture box...
0
by: Özden Irmak | last post by:
Hello, In my application, I've to cast DocumentDesigner class to my own derived class,MyDocumentDesigner, in order to reach the protected properties in DocumentDesigner class. But everytime I...
13
by: Jack MacRank | last post by:
Hello, I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003 Pro on WinXP SP2 using IIS 5.1). I created a seperate "data" class to house all the MySQL connection and sql...
11
by: Roy Lawson | last post by:
I have no idea what is going on here. I wrote a simple application in VB.NET to generate a Crystal Report, and I am now trying to move it to ASP.NET with Crstal Enterprise. I wish I could tell...
8
by: Charles | last post by:
I do not understand why I am getting a "Specified cast is not valid" error, since it has worked before. Something has changed and I am not really sure what it could be. I am looking for something...
2
by: Fabian | last post by:
Hi, I work with asp.net 2.0 and I have a intermittent error, only happens a few times a day. In the page I evaluate a Query String and then I get data form a database. The code snipped: ...
1
by: Kevin O`Brien | last post by:
I was reading my new asp.net book last night and thought I'd give mobile devices a go. I use Web Matrix, however when I went to create a new mobile page this morning, it displayed a dialog box...
3
by: keithb | last post by:
Using a GridView, I get a "Specified cast is not valid" error when binding the Visible propery of a hyperlink control to a DataTable text field. The error goes away if I replace the data binding...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.