Convert IEnumerable to EntitySet
Posted
by Gregorius
on Stack Overflow
See other posts from Stack Overflow
or by Gregorius
Published on 2010-05-17T00:34:50Z
Indexed on
2010/05/17
0:40 UTC
Read the original article
Hit count: 1003
Hey all,
Hoping somebody can shed some light, and perhaps a possible solution to this issue I'm having...
I have used LINQ to SQL to pull some data from a database into local entities. They are products from a shopping cart system. A product can contain a collection of KitGroups (which are stored in an EntitySet (System.Data.Linq.EntitySet). KitGroups contain collections of KitItems, and KitItems can contain Nested Products (which link back up to the original Product type - so its recursive).
From these entities I'm building XML using LINQ to XML - all good here - my XML looks beautiful, calling a "GenerateProductElement" function, which calls itself recursively to generate the nested products. Wonderful stuff.
However, here's where i'm stuck.. i'm now trying to deserialize that XML back to the original objects (all autogenerated by Linq to SQL)... and herein lies the problem. Linq tO Sql expects my collections to be EntitySet collections, however Linq to Xml (which i'm tyring to use to deserailise) is returning IEnumerable.
I've experimented with a few ways of casting between the 2, but nothing seems to work... I'm starting to think that I should just deserialise manually (with some funky loops and conditionals to determine which KitGroup KitItems belong to, etc)... however its really quite tricky and that code is likely to be quite ugly, so I'd love to find a more elegant solution to this problem.
Any suggestions?
Here's a code snippet:
private Product GenerateProductFromXML(XDocument inDoc)
{
var prod = from p in inDoc.Descendants("Product")
select new Product
{
ProductID = (int)p.Attribute("ID"),
ProductGUID = (Guid)p.Attribute("GUID"),
Name = (string)p.Element("Name"),
Summary = (string)p.Element("Summary"),
Description = (string)p.Element("Description"),
SEName = (string)p.Element("SEName"),
SETitle = (string)p.Element("SETitle"),
XmlPackage = (string)p.Element("XmlPackage"),
IsAKit = (byte)(int)p.Element("IsAKit"),
ExtensionData = (string)p.Element("ExtensionData"),
};
//TODO: UUGGGGGGG Converting b/w IEnumerable & EntitySet
var kitGroups = (from kg in inDoc.Descendants("KitGroups").Elements("KitGroup")
select new KitGroup
{
KitGroupID = (int) kg.Attribute("ID"),
KitGroupGUID = (Guid) kg.Attribute("GUID"),
Name = (string) kg.Element("Name"),
KitItems = // THIS IS WHERE IT FAILS - "Cannot convert source type IEnumerable to target type EntitySet..."
(from ki in kg.Descendants("KitItems").Elements("KitItem")
select new KitItem
{
KitItemID = (int) ki.Attribute("ID"),
KitItemGUID = (Guid) ki.Attribute("GUID")
});
});
Product ImportedProduct = prod.First();
ImportedProduct.KitGroups = new EntitySet<KitGroup>();
ImportedProduct.KitGroups.AddRange(kitGroups);
return ImportedProduct;
}
© Stack Overflow or respective owner