views:

386

answers:

1

Hi,

I'm currently using LINQ to SQL for data retrieval and then populating my custom objects with LINQ queries. My custom objects inherit from a base class that uses the IsReference = true attribute in the datacontract. I'm then taking my object hierarchy and serializing it to XML which is then sent off to a service.

This works however what's happening in the XML is that the object data is repeated for objects throughout the file. What I'm wanting in the XML file is that if an object has the same data as another object of the same type (regardless of where it sits in the object tree) I'd like it to have a reference to that first object and not repeat the data.

I'm needing some object tracking and not sure if it can be handled at the LINQ DataContext level or since I'm instantiating my own custom objects if I should track it at that level using something like a hashtable for each object type.

Here's what my classes look like:

class Section1 { 
  public static MyClass GetClasses(int Id)
  {
    using (DataContext dataContext = new DataContext())
    {
      var result = from items in dataContext.Table
        where item.Id == Id
        select items;

      foreach (var entry in result)
      {
        MyClass myClass = new MyClass();
        myclass.Id = entry.Id;
      }
    }
   return myclass;
  }
}

Later on in my program I'm creating another list of the same type of items as a method in another class and I expect some of the results to be the same as in the first call:

Class2 {
  public static MyClass GetItemClasses(int ItemId)
  {
    MyClass myClass = new MyClass();

    using (DataContext dataContext = new DataContext())
    {
      var result = from items in dataContext.Table
          where item.Id == ItemId
          select items;

      foreach (var entry in result)
      {
        MyClass myClass = new MyClass();
        myclass.Id = entry.Id;
      }
    }
   return myclass;
  }
}

Doing this successfully populates all my objects which I then serialize. Any ideas on how I can have references in my XML file for those objects that are repeated?

Thanks for any input.

+1  A: 

Thought I'd update this as I've found a workable solution.

Since my custom objects are separate from my DataContext and not tracked by it I went ahead and created a lookup table for my objects and I check that table before instantiating a new object.

This has provided me with the references in the XML file that I was after.

Zero Cool