Home » Featured, Headline, Web Development

Linq to SQL Hierarchical Data Serialization Problem (and fix)

4 January 2010 No Comment
Linq to SQL Hierarchical Data Serialization Problem (and fix)

I had a weird Serialization problem with Linq to SQL the other day and since I didn’t Google the fix I figured I’d publish it here.

I had a table which refers to itself, something like this:


CREATE TABLE [dbo].[node](
[id] [int] IDENTITY(1,1) NOT NULL,
[title] [nvarchar](50) NOT NULL,
[parentId] [int] NULL,
CONSTRAINT [PK_node] PRIMARY KEY CLUSTERED
(
[id] ASC
)
ALTER TABLE [dbo].[node]  WITH CHECK ADD  CONSTRAINT [FK_node_node] FOREIGN KEY([parentId])
REFERENCES [dbo].[node] ([id])

I have a stored function to retrieve all the nodes, including their descendants from the DB, mine’s based on the function included here [LINK]

Once I got the rows, I was able to convert these into an object graph based on the relationship which I’d added in the DBML layout. I set “Serialization” as “Unidirectional” on the layout. No issues.

The issue I had was in Serialization.  I wanted JSON from this structure. When I serialized I was getting only the top-most entry. So I stepped through the debugger and found I was getting ALL the entries when stepping through. Running the code I was getting only partial. For some reason stepping through the code forced .NET to instantiate the full object graph but I could not figure out why.

My initial thought was that L2S was doing some lazy-loading of the data but that made no sense since the stored function was retrieving all the rows in one shot.  I couldn’t figure it out.

In the end, since performance is not an issue (this is a design-time-pre-compiled bit of JSON I’m generating) I added a simple function to recursively iterate each node :


public static void ParseObj(node s){
foreach (node v in s.children)
{
// do nothing
ParseObj(v);
}

I did experiment with LoadOptions and also made sure Delay Loading was turned off but these made no difference (as expected). Weird and possibly a bug.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.