Assuming I have some data in the form of
Customer1
Name
Address
Order1
ID
Products
Product1
ID
Product2
ID
Customer2
...
Us开发者_Python百科ing the following class to represent it
class Customer
{
public String name { get; set; }
public String Address {get; set;}
public List<OrderInfo> Orders { get; set; }
}
class Order
{
public int ID { get; set; }
public List<Product> Products { get; set; }
}
class Product
{
public int ID { get; set; }
}
I'd like to use XML serialization to read/write the data instead of using the entities framework and SQL. With the entities framework I'd be able to define a many to one relationship so that each product would only be stored once in the database and each order would just reference it. Using the above code with XML serialization it's my understanding that there would be many copies of each product stored (both in memory and the XML file).
To fix that I could just store a list of product IDs instead of to products themselves and then just serialize a separate collection of 'products' to another XML file - but that doesn't strike me as a clean solution.
Another idea would be to have a RepositoryClass which contained a list of customers and products. The customers would then only need to store the productIDs and when you requested a 'customer' from the repo it would handle the looking up and building the above objects so the rest of my code wouldn't have to worry about how the data was stored. Does that sound like a better solution? How would you do it?
The other requirement for the solution it that I want it as easy as possible to hook up the solution to GUI to edit the properties directly (that's actually why I wish there a way to store it all in one XML file that I could just bind to a WPF window).
Thanks in advance for your thoughts and advice!
There would be no copies stored in memory because you could instantiate a specific product once and refer to that product from then on.
The xml case is a little more complicated. The xml specification does have a solution for this, but I'm not sure how well the .NET framework supports this. You could have an xml document like this:
<rootElement>
<Customers>
<Customer ...>
<Order>
<ProductRef ref="1" />
<ProductRef ref="2" />
</Order>
</Customer>
</Customers>
<Products>
<Product id="1" />
<Product id="2" />
<Product id="3" />
<Product id="4" />
</Products>
</rootElement>
A validating XML parser will validate that id
's are unique within the document and that each ref
attribute actually refers to an id
if you specify a DTD or XML schema that requires this.
Of course you'd still have to build something that parses this structure but you no longer have duplicate xml data.
The DataContractDeserializer in .NET has a constructor argument called preserveObjectReferences. If this argument is set to true (default is false) the identity of the objects is preserved. For more information: http://msdn.microsoft.com/en-us/library/ms731073.aspx
精彩评论