在这种情况下,我尝试使用LINQ to XML和LINQ to SQL从XML文件导入数据到数据库.
这是我的LINQ数据模型:
public struct Page { public string Name; public char Status; public EntitySetPageContents; } public struct PageContent { public string Content; public string Username; public DateTime DateTime; }
基本上我正在尝试做的是编写一个查询,它将为我提供一个数据结构,我可以提交给我的LINQ数据上下文.
IEnumerablepages = 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() };
问题出在子查询中.我必须以某种方式将我的对象集合放入EntitySet容器中.我无法施放它(哦,我已经尝试过了)并且没有EntitySet()构造函数似乎有所帮助.
那么,我可以编写一个LINQ查询,用我的IEnumerable
你可以使用辅助类从IEnumerable构造你的实体集,例如:
public static class EntityCollectionHelper { public static EntitySetToEntitySet (this IEnumerable source) where T:class { EntitySet set = new EntitySet (); set.AddRange(source); return set; } }
并像这样使用它:
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()