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:
public static class EntityCollectionHelper
{
public static EntitySet<T> ToEntitySet<T>(this IEnumerable<T> source) where T:class
{
EntitySet<T> set = new EntitySet<T>();
set.AddRange(source);
return set;
}
}
and use it like so :
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)
}).ToEntitySet()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With