【问题标题】:Convert NHibernate IList to List in C#在 C# 中将 NHibernate IList 转换为列表
【发布时间】:2011-04-28 14:44:21
【问题描述】:

我有 NHibernate IList。我想转换为列表。请帮帮我。

这是我的代码

IList<Tag> list = Tag.GetAll();

我想把它转换成列表

public class CategoryTag
{
    public int ID { get; set; }
    public string TagName { get; set; }

    public CategoryTag()
    {

    }

    public List<CategoryTag> GetCategoryTagList()
    {
         IList<Tag> list = Tag.GetAll();

         // How do I return Tag as List?

        return tagList;
    }
}

更新

我想更新我的问题,因为我的问题没有得到很好的解释。

这是我将其传递给 jQuery UI 自动完成的代码:

[WebMethod]
    public IList<Tag> FetchTagList(string tag)
    {
        var ctag = new List<Tag>(Tag.GetAll())
            .Where(m => m.TagName.ToLower().StartsWith(tag.ToLower()));
        return ctag.ToList();
    }

我收到以下错误:

无法序列化接口 System.Collections.Generic.IList`1[[QuestionCenter.Domain.Tag, QuestionCenter.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]。

将我的 IList 传递给 JSON 的任何解决方案都会对我有所帮助。谢谢。

【问题讨论】:

标签: c# nhibernate list ilist


【解决方案1】:

使用 LINQ:

return tagList.ToList();

【讨论】:

    【解决方案2】:

    使用 .ToList() 扩展方法:

    return list.ToList()
    

    【讨论】:

      【解决方案3】:

      您需要将返回类型更改为 Tag[] 并使用 ToArray() 而不是 ToList()。 IIRC,您不能在 webmethod 中序列化 IList。

      【讨论】:

        【解决方案4】:

        return Tag.GetAll().ToList() 对你不起作用?

        【讨论】:

        • 因为它是 NHibernate IList。我需要将其转换为列表。
        • 没有。 IList 不是 nhibernate 发明的。您的意思是您需要将 Tag 列表转换为 CategoryTag 列表,这是您的 DTO。
        • 基本上我想要做的是,通过 Webservice 将 NHibernate IList 传递给 JSON。 CategoryTag 类只是将 IList 转换为 List 的中间人。如果可以将 IList 传递给带有 Tag 类的 JSON,我就不需要 CategoryTag 类。
        • @D 先生:嗯,您必须将 Tag 映射到 CategoryTag。您可以自己进行从左到右的分配或使用 AutoMapper 对象到对象映射器。
        【解决方案5】:
        var myList = Tag.GetAll()
                         .ConvertAll(tag => new CategoryTag{ Id = tag.Id, XXX = tag.YYY})
                         .ToList();
        

        更新

        根据您对答案的评论,我会改用AutoMapper

        【讨论】:

        • 就像我说的那样,它是 NHibernate IList。我的代码出现此错误: 错误 1 ​​无法将类型 'System.Collections.Generic.List' 隐式转换为 'System.Collections.Generic.List' D:\ MyFiles\QuestionCenter\QuestionCenter.Website\QuestionCenter.Website\CategoryTag.cs​​ 23 21 QuestionCenter.Website
        • 我收到以下错误无法序列化 System.Collections.Generic.IList`1[[QuestionCenter.Domain.QuestionTag, QuestionCenter.Domain, Version= 类型的成员 QuestionCenter.Domain.Tag.QuestionTags 1.0.0.0, Culture=neutral, PublicKeyToken=null]] 因为它是一个接口。
        猜你喜欢
        • 1970-01-01
        • 2012-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多