簡體   English   中英

你如何投射 IEnumerable<t> 或可查詢<t>實體集<t> ?</t></t></t>

[英]How do you cast an IEnumerable<t> or IQueryable<t> to an EntitySet<t>?

在這種情況下,我嘗試使用 LINQ 到 XML 和 LINQ 到 SQL 執行從 XML 文件到數據庫的數據導入。

這是我的 LINQ 數據 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;
}

基本上我想做的是編寫一個查詢,該查詢將為我提供一個數據結構,我可以將其提交到我的 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()
                };

問題出在子查詢中。 我必須以某種方式將我的 object 集合放入 EntitySet 容器中。 我無法施放它(天哪,我怎么試過)而且沒有 EntitySet() 構造函數似乎有幫助。

那么,我能否編寫一個 LINQ 查詢,用我的 IEnumerable<Page> 數據填充 EntitySet<PageContent> 數據?

您可以使用幫助器 class 從 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM