In this situation I am trying to perform a data import from an XML file to a database using LINQ to XML and LINQ to SQL.
Here’s my LINQ data model:
public struct Page { public string Name; public char Status; public EntitySet<PageContent> PageContents; } public struct PageContent { public string Content; public string Username; public DateTime DateTime; }
Basically what I’m trying to do is write a query that will give me a data structure that I can just submit to my LINQ Data Context.
IEnumerable<Page> pages = from el in doc.Descendants() where el.Name.LocalName == 'page' select new Page() { Name = el.Elements().Where(e => e.Name.LocalName == 'title').First().Value, Status = 'N', PageContents = (from pc in el.Elements() where pc.Name.LocalName == 'revision' select new PageContent() { Content = pc.Elements().Where(e => e.Name.LocalName=='text').First().Value, Username = pc.Elements().Where(e => e.Name.LocalName == 'contributor').First().Elements().Where(e => e.Name.LocalName == 'username').First().Value, DateTime = DateTime.Parse(pc.Elements().Where(e => e.Name.LocalName == 'timestamp').First().Value) }).ToList() };
The problem is in the sub-query. I have to somehow get my object collection into the EntitySet container. I can’t cast it (oh lord how I’ve tried) and there’s no EntitySet() constructor that would seem to help.
So, can I write a LINQ query that will populate the EntitySet<PageContent> data with my IEnumerable<Page> data?
you can construct your entity set from a IEnumerable using a helper class, something like:
and use it like so :