如何 return 我的自定义模型的 IEnumerable<>?

how return an IEnumerable<> of my customized model?

我正在使用 EF6,我的模型名称之一是 tblAttachLabel。我已经定制了名称为 AttachLabel 的模型。我需要我的自定义模型的 IEnumerable,它填充了 tblAttachLabel 模型。很容易return

IEnumerable<tblAttachLabel> 

来自我的函数,但我需要 return

IEnumerable<AttachLabel>

所以我做了这个代码:

public static IEnumerable<AttachLabel> GetAttachLabel()
    {            
        Entities db = new Entities();
        var x = from al in db.tblAttachLabels select al;

        List<AttachLabel> temp = new List<AttachLabel>();
        IEnumerable<AttachLabel> _attachLabel;
        foreach (var item in x)
        {
            AttachLabel a = new AttachLabel()
            {
                ID = item.ID,
                Text = item.Text
            };
            temp.Add(a);
        }
        _attachLabel = temp;

        return _attachLabel;
    }

但我知道当我将 List 用于 temp 时,查询将执行,但我不希望这样。那么我如何 return 一个 IEnumerable ?

试试这个:

public static IEnumerable<AttachLabel> GetAttachLabel()
{
    Entities db = new Entities();

    return from item in db.tblAttachLabels select new AttachLabel()
    {
        ID = item.ID,
        Text = item.Text
    };
}

@haim770 答案的另一种可能性和替代方法是使用 yield 关键字的循环:

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

public static IEnumerable<AttachLabel> GetAttachLabel()
{               
    using(Entities db = new Entities())
    {
        foreach (var item in db.tblAttachLabels)
        {
            AttachLabel a = new AttachLabel()
            {
                ID = item.ID,
                Text = item.Text
            };
            yield return a;
        }
    }
    yield break;
}

你的上下文也应该被处理掉,所以我添加了一个 using 语句。

并且不需要:

from al in db.tblAttachLabels select al;

因为它只是 returns 与 db.tblAttachLabels 相同的集合。

public static IEnumerable<AttachLabel> GetAttachLabel()
{
    Entities db = new Entities();
    var items = from al in db.tblAttachLabels select al;

    return items.Select(new AttachLabel()
    {
       ID = item.ID,
       Text = item.Text
    });

}

其中之一,取决于您是否喜欢 lambda 表达式:

public static IEnumerable<AttachLabel> GetAttachLabel()
{
    using (var db = new Entities())
    {
        return db.tblAttachLabels.Select(item => new AttachLabel
        {
            ID = item.ID,
            Text = item.Text
        });
    }
}

与否:

public static IEnumerable<AttachLabel> GetAttachLabel()
{
    using (var db = new Entities())
    {
        return from item in db.tblAttachLabels
                select new AttachLabel
                {
                    ID = item.ID,
                    Text = item.Text
                };
    }
}