473,545 Members | 529 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.InvalidC astException
Source: System.Data.Lin q
TargetSite: Boolean TryCreateKeyFro mValues(System. Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Sin gleKeyManager`2 .TryCreateKeyFr omValues(Object[] values, V& v)
at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Ide ntityCache`2.Fi nd(Object[] keyValues)
at System.Data.Lin q.IdentityManag er.StandardIden tityManager.Fin d(MetaType
type, Object[] keyValues)
at System.Data.Lin q.CommonDataSer vices.GetCached Object(MetaType type,
Object[] keyValues)
at System.Data.Lin q.ChangeProcess or.GetOtherItem (MetaAssociatio n assoc,
Object instance)
at System.Data.Lin q.ChangeProcess or.BuildEdgeMap s()
at System.Data.Lin q.ChangeProcess or.SubmitChange s(ConflictMode failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges(Co nflictMode failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges()

(.....)

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

This error is being thrown on the following code:
============
ResponseDataCon text db = new ResponseDataCon text(m_Connecti onString);
CodebookVersion codebookVersion = db.CodebookVers ions.Single(cv =>
cv.VersionTag == m_CodebookVersi onTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionN ame = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion .ResponseCodes. Add(rc);
db.SubmitChange s(); //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 'responseCodeTa bleId' and is of type: INT
NOT NULL

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

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

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

tblResponseCode Table's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTab leId int
surveyQuestionN ame 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 12419
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.Lo g - Logging LINQ To SQL Output to Console or Debugger Output
Window
http://www.davidhayden.com/blog/dave...ntextLogLoggin
gLINQToSQLOutpu tConsoleDebugge rOuputWindow.as px

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****@microsof t.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?UGF1bCBQcmV 3ZXR0?= <li***@communit y.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.InvalidC astException
Source: System.Data.Lin q
TargetSite: Boolean TryCreateKeyFro mValues(System. Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Sin gleKeyManager`2 .
TryCreateKeyFro mValues(Object[] values, V& v)
at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Ide ntityCache`2.Fi n
d(Object[] keyValues)
at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Fin d(MetaType
>type, Object[] keyValues)
at System.Data.Lin q.CommonDataSer vices.GetCached Object(MetaType type,
Object[] keyValues)
at System.Data.Lin q.ChangeProcess or.GetOtherItem (MetaAssociatio n assoc,
Object instance)
at System.Data.Lin q.ChangeProcess or.BuildEdgeMap s()
at System.Data.Lin q.ChangeProcess or.SubmitChange s(ConflictMode
failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges(Co nflictMode failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges()

(.....)

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

This error is being thrown on the following code:
============
ResponseDataCon text db = new
ResponseDataCon text(m_Connecti onString);
CodebookVersion codebookVersion = db.CodebookVers ions.Single(cv
=>
>cv.VersionTa g == m_CodebookVersi onTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionN ame = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion .ResponseCodes. Add(rc);
db.SubmitChange s(); //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 'responseCodeTa bleId' and is of type:
INT
>NOT NULL

codebookVersio n (parent class) maps to table tblResponseCode Table
responseCode (childClass) maps to table tblResponseCode

If I execute SQL directly, it works. e.g.
INSERT INTO tblResponseCode
(responseCodeT ableId, surveyQuestionN ame, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
Updates to the same class work properly. e.g.
codebookVersio n.ResponseCodes[0].Description = "BlahBlahBl ah";
db.SubmitChang es(); //no exception - change is committed to db

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

tblResponseCod eTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTa bleId int
surveyQuestion Name 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.

tblResponseTabl e definition (which maps to CodebookVersion )
COLUMN_NAME TYPE_NAME
id int identity
versionTag nvarchar
responseVersion Tag 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.Lo g - Logging LINQ To SQL Output to Console or Debugger Output
Window
http://www.davidhayden.com/blog/dave...ntextLogLoggin
gLINQToSQLOutpu tConsoleDebugge rOuputWindow.as px

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****@microsof t.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?UGF1bCBQcmV 3ZXR0?= <li***@communit y.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.InvalidC astException
Source: System.Data.Lin q
TargetSite: Boolean TryCreateKeyFro mValues(System. Object[], V ByRef)
HelpLink: null
Stack: at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Sin gleKeyManager`2 .
TryCreateKeyFro mValues(Object[] values, V& v)
at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Ide ntityCache`2.Fi n
d(Object[] keyValues)
at
System.Data.Lin q.IdentityManag er.StandardIden tityManager.Fin d(MetaType
type, Object[] keyValues)
at System.Data.Lin q.CommonDataSer vices.GetCached Object(MetaType type,
Object[] keyValues)
at System.Data.Lin q.ChangeProcess or.GetOtherItem (MetaAssociatio n assoc,
Object instance)
at System.Data.Lin q.ChangeProcess or.BuildEdgeMap s()
at System.Data.Lin q.ChangeProcess or.SubmitChange s(ConflictMode
failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges(Co nflictMode failureMode)
at System.Data.Lin q.DataContext.S ubmitChanges()

(.....)

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

This error is being thrown on the following code:
============
ResponseDataCon text db = new
ResponseDataCon text(m_Connecti onString);
CodebookVersion codebookVersion = db.CodebookVers ions.Single(cv
=>
cv.VersionTag == m_CodebookVersi onTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionN ame = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion .ResponseCodes. Add(rc);
db.SubmitChange s(); //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 'responseCodeTa bleId' and is of type:
INT
NOT NULL

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

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

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

tblResponseCode Table's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTab leId int
surveyQuestionN ame 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 (ResponseDataCo ntextDataContex t ctx = new
ResponseDataCon textDataContext ())
{

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

MessageBox.Show (codebookVersio n.ToString());

ResponseCode rc = new ResponseCode()
{
surveyQuestionN ame= "Q11",
code = 3,
description = "Yet another code"
};
codebookVersion .ResponseCodes. Add(rc);
ctx.SubmitChang es();
=============== =

# 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].[responseVersion Tag],
[t0].[dtCreate]
FROM [dbo].[tblResponseTabl e] AS [t0]
WHERE [t0].[id] = @p0
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [2]
-- Context: SqlProvider(Sql 2005) Model: AttributedMetaM odel Build:
3.5.21022.8

INSERT INTO [dbo].[tblResponseCode Table]([responseCodeTab leId],
[surveyQuestionN ame], [code], [description], [dtCreate])
VALUES (@p0, @p1, @p2, @p3, @p4)

SELECT CONVERT(Int,SCO PE_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(Sql 2005) Model: AttributedMetaM odel 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****@microsof t.com.
--------------------
>From: =?Utf-8?B?UGF1bCBQcmV 3ZXR0?= <li***@communit y.nospam>
References: <BB************ *************** *******@microso ft.com>
<HQ************ **@TK2MSFTNGHUB 02.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.

tblResponseTab le definition (which maps to CodebookVersion )
COLUMN_NAME TYPE_NAME
id int identity
versionTag nvarchar
responseVersio nTag 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.L og - Logging LINQ To SQL Output to Console or Debugger
Output
>Window
http://www.davidhayden .com/blog/dave/archive/2007/08/17/DataContextLogL oggin
>gLINQToSQLOutp utConsoleDebugg erOuputWindow.a spx

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
3616
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: "Specified cast is not valid." The only thing i put there was a "test this." inside the form. What might be the problem here? Thanks in advance. ...
1
5815
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 which is an OLE Object located in the Page Header section of my .RPT file. This is the call which works perfectly in VB6 to format the crystal...
0
1501
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 get a "Specified cast not valid!" error... MyDocumentDesigner FDDesigner = ((MyDocumentDesigner)DHost.GetDesigner((IComponent)CForm));
13
28238
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 command methods. This is exactly what the Microsoft Data Access Application Block assembly does but I coded my own simple, custom class. I have a...
11
3100
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 you how the report works...but I can't even get past connecting to the database :-) I use the typical: Dim oConnection As New...
8
1787
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 along the lines of did you check this, have you did this, or this is the wrong way of doing this. I can access the CColPositions and the CPosition...
2
3084
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: try {
1
1425
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 with the message: "specified cast is not valid" The file seems to be getting created, but does not open. I get the same error when I try to open...
3
3684
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 statement with "true" or "false". This code causes the error: <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#...
0
7465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.