Eric Litovsky

For almost an entire day I have been trying to figure out why I was getting weird errors when calling SubmitChanges() on my datacontext.

As I was working on an STS / Cardspace solution I ran into this:

An example of what I was doing:

Code Snippet

ManagedCardTypeClaim mc = new ManagedCardTypeClaim

{

ManagedCardTypeiD = ctypeid, //int

BaseClaim = bc, //typed LINQ object

ClaimCustomDisplay = s, //string

ManagedCardType = mct, //string

ClaimCustomDescription = dsc, //string

Claim = ctype //string

};

stc.ManagedCardTypeClaims.Add(mc);

stc.SubmitChanges();

Real basic insert functionality collapsed when I had these "track changes" enabled. The error I would get from this code is NullReferenceException. When I removed the entry for BaseClaim, I would get an Invalid Cast exception.

Niether of these exceptions would give me much to go on except a cryptic call stack so deep in the bowels of LINQ that I couldn't make any sense of it. The first type (NullReferenceException) brought me here:

at System.Data.Linq.ChangeTracker.StandardChangeTracker.IsFastTracked(Object obj)
at System.Data.Linq.ChangeTracker.StandardChangeTracker.GetTrackedObject(Object obj)
at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()

The Invalid Cast Exception brought me here:

at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v)
at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues)
at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)

Not very revealing.

I discovered that I probably have the worst developer karma on this board as I always seem to stumble upon the issues nobody else has seen and have to spend hours stumbling around blindly until I get lucky. Ok, enough of the violins. Here's what I finally was able to figure out.

In my schema I have a relationship between BaseClaims and ManagedCardTypeClaims with BaseClaims being the Parent table. The problem is, the foreign key is not attached to the Parent's PK, but instead to a column with a unique constraint. According to Database Practice, this is an acceptable relationship as the unique constraint is indexed. But LINQ chokes on this. I'm not sure if this behavior is by design, but I see it as a limitation. There are many valid instances when a table with multiple unique columns should be able to relate to foreign tables, but if LINQ can't suport this, I'm back to writing in-line command sql. Yuck.

Can anyone tell me if there's a way to do what I need to do or do I need to wait for a future release

Thanks.



Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Matt Warren - MSFT

Yes, this is a bug. We'll try to reproduce it.




Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Eric Litovsky

Hey, Matt.

Any success with reproducing this

Is there a reasonable workaround


Thanks for the post.

Eric.





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Matt Warren - MSFT

I believe we've determine that this was a problem we already fixed. It should succeed when Beta 2 comes out.




Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Ing. Andreas Pollak

After using UserName from the table aspnet_User to link the user to other new created tables and using Beta 2 this error still occurs :-(. Can anybody verify this

Thnx

Andreas





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

StillWaiting

Confirmed. It still occurs null reference error.




Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

ulab

FYI, my whole day wasted on InvalidCastException and NullReferenceException.





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Pablo_Marambio

Is this still an open issue Is this effectively being treated as a bug inside the LINQ [Developer] Team





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

timlajaunie

This is happening for any class that has a composite key. And, depending on how many properties participate in the key, the exception occurs at either

SingleKeyManager.TryCreateKeyFromValues(object[] values, out V v)

or

MultiKeyManager.TryCreateKeyFromValues(object[] values, out IdentityManager.StandardIdentityManager.MultiKey<V1, V2> k)





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Kce

Re bug,

After spending several days getting on the Linq train, my first 'save' in a real application and I get the same issue, this is basic stuff.

Please let us know if the issue is going to be fixed soon, or do I dump Linq before I start..

Casey





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

WallyN

I am having the same problem with trying to SubmitChanges and getting the error InvalidCastException. I have a very simple situation. I have a Parent table and a Child table with a OneToOne Association based on non-primary keys.

The following LINQ statement gives me the Parent and Child objects:

var parent = (Parent from DataSource.Contect.Parents where Parent.code == 'X123' select new { Parent }).ToList();

But if I change anything in the Child object and then SubmitChanges I get the InvalidCastException error. Is there something I am doing wrong Do I need an update

Please respond,

Thanks.

I am using the following, and the stack dump follows:

Microsoft Visual Studio 2008
Version 9.0.21022.8 RTM
Microsoft .NET Framework
Version 3.5

Installed Edition: Enterprise

Microsoft Visual Basic 2008 91904-270-4265031-60629
Microsoft Visual Basic 2008

Microsoft Visual C# 2008 91904-270-4265031-60629
Microsoft Visual C# 2008

Microsoft Visual C++ 2008 91904-270-4265031-60629
Microsoft Visual C++ 2008

Microsoft Visual Studio 2008 Tools for Office 91904-270-4265031-60629
Microsoft Visual Studio 2008 Tools for Office

Microsoft Visual Studio Team System 2008 Development Edition 91904-270-4265031-60629
Microsoft Visual Studio Team System 2008 Development Edition

Portions of International CorrectSpell spelling correction system c 1993 by Lernout & Hauspie Speech Products N.V. All rights reserved.

The American HeritageR Dictionary of the English Language, Third Edition Copyright c 1992 Houghton Mifflin Company. Electronic version licensed from Lernout & Hauspie Speech Products N.V. All rights reserved.


Microsoft Visual Web Developer 2008 91904-270-4265031-60629
Microsoft Visual Web Developer 2008

Crystal Reports AAJ60-G0MSA4K-68000CF
Crystal Reports Basic for Visual Studio 2008


Hotfix for Microsoft Visual Studio Team System 2008 Development Edition - ENU (KB945282) KB945282
This hotfix is for Microsoft Visual Studio Team System 2008 Development Edition - ENU.
If you later install a more recent service pack, this hotfix will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/945282.

The InvalidCastException Details follow:

System.InvalidCastException was unhandled
Message="Specified cast is not valid."
Source="System.Data.Linq"
StackTrace:
at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v)
at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues)
at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at Caselink.Window1.Button_Click(Object sender, RoutedEventArgs e) in C:\Projects\Visual Studio 2008 Projects\Caselink\Caselink\Window1.xaml.cs:line 598
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Caselink.App.Main() in C:\Projects\Visual Studio 2008 Projects\Caselink\Caselink\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

BobFr

Same problem here -- I tried the hotfix URL but it failed.

Did it go away or is it not yet ready I did apply a previous hotfix - KB936252 (and will reapply it just in case -- it's SQL 2005 SP2 #3186 for 64 bit. I'm actually using SQL Express on Vista64 so it may not be applicable.

The larger problem is the difficulty of debugging these problems because of the lack of any identifying information in the trace back. This is a pervasive problem ¨C silent failures and failures that kill VS. I realize this is first a generation and very much appreciate how well it works but it makes it even more important to provide as much diagnostic information as possible. Especially since I¡¯m not facile enough with the new capabilities to distinguish between a bug and a feature.

As an FYI here¡¯s my shorter traceback

[0]: "System.InvalidCastException: Specified cast is not valid.\r"

[1]: " at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v)\r"

[2]: " at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues)\r"

[3]: " at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues)\r"

[4]: " at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues)\r"

[5]: " at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)\r"

Devil: " at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()\r"

[7]: " at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)\r"

Music: " at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)\r"

[9]: " at System.Data.Linq.DataContext.SubmitChanges()\r"

[10]: " at rmfADOUtils.DCAssist.SubmitChanges() in Y:\\dev\\rmf\\rmfADOUtils\\DCAssist.cs:line 116"

Once I hit a bug like this how do I reset the connection

PS: Those emoticons were inserted by the forum program -- not me (except this one )





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

timlajaunie

The last time I saw this error, it occured when the parent side of the assocation had only parts of its key used. I had an invoice entity associated with an office by office code ('H', 'L', 'S', etc). The key for the office entity was actually the code and name. As soon as I changed the key on the office entity to be only the code, I was able to submit changes. We wound up determining that the code, alone, is a more appropriate key than the code + name. So, after correcting the database schema, our particular situation was corrected.

You may want to check for this situation. While our particular case wound up being a database design issue, there may be a case where this type of situation is valid; thus exposing a weakness in LINQ to SQL.





Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

Eric Litovsky

Just an update to my initial post.

LINQ and I have become better at sorting out what's what. Ultimately I don't think LINQ is mature enough to handle complex data models as efficiently as I would like, but it more than makes up for this with it's robust support of Stored Procs and UDFs. Any database that complies with the 3rd normal form can easily implement LINQ and I have already deployed 2 successful enterprise-scale solutions using the LINQ-To-SQL architecture without any problems.

Knowing where the limitations are allows me to accomodate them in my design. Complex data-relations can be managed in SQL Server through the use of procs and functions. BASIC CRUD functionality is well supported in LINQ and works without a hitch. That combined with Lambda expressions is a great way to manipulate records and anonymous, bindable types are a great way to create dynamic data chunks for viewing and updating.

Overall LINQ is a good piece of work which in time will grow into standard data layer for a while to come. If you're having issues with LINQ, my first suggestion would be to review your data model. Study your design and see where it can be improved and simplified, generally I have not found a significant case for supporting non-PK relationships aside from backwards-compatibility to databases which were poorly designed to begin with. And if you're hooking into a legacy database who's diagram looks like a plate of spaghetti and meatballs you probably have a complex logic layer set up for CRUD already and should probably stay away from LINQ for now.

Eric.




Re: LINQ Project General Non-Primary Keys and LINQ to SQL Problems (is this a bug)?

BobFr

I worked around this by writing an SQL update for each of the record types and then do a refresh to read the record back so that the update is satisfied.

As an FYI ¨C in subclass of the DataContext

public new void SubmitChanges() {

bugCheck();

base.SubmitChanges();

}

private void bugCheck() {

var cs = this.GetChangeSet();

bugCheck(cs.Updates);

}

private void bugCheck(IList<object> iu) {

foreach (var row in iu) {

if (row is typeA)

SaveTypeA(row as TypeA);

else if (row is TypeB)

SaveTypeB(row as TypeB);

else

continue;

this.Refresh(RefreshMode.OverwriteCurrentValues, row);

}

}