gpt4 book ai didi

c# - 如何将 IEnumerable 或 IQueryable 转换为 EntitySet

转载 作者:可可西里 更新时间:2023-11-01 08:17:59 24 4
gpt4 key购买 nike

在这种情况下,我尝试使用 LINQ to XML 和 LINQ to SQL 执行从 XML 文件到数据库的数据导入。

这是我的 LINQ 数据模型:

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;
}

基本上我想做的是编写一个查询,该查询将为我提供一个数据结构,我可以将其提交到我的 LINQ 数据上下文。

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()
};

问题出在子查询上。我必须以某种方式将我的对象集合放入 EntitySet 容器中。我无法施放它(天哪,我怎么试过)而且没有 EntitySet() 构造函数似乎有帮助。

那么,我能否编写一个 LINQ 查询,用我的 IEnumerable 数据填充 EntitySet 数据?

最佳答案

您可以使用辅助类从 IEnumerable 构造您的实体集,例如:

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;
}
}

并像这样使用它:

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()

关于c# - 如何将 IEnumerable<t> 或 IQueryable<t> 转换为 EntitySet<t>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/100851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com