如何返回我的自定义模型的 IEnumerable<>
本文关键字:模型 IEnumerable 自定义 我的 何返回 返回 | 更新日期: 2023-09-27 18:35:45
我正在使用EF6,我的模型名称之一是tblAttachLabel。 并且我已经自定义了名称为AttachLabel的模型。我需要一个 IEnumerable 的自定义模型,填充 tblAttachLabel 模型。退货非常容易
IEnumerable<tblAttachLabel>
从我的函数,但我需要返回
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 作为临时查询时,查询将执行,但我不想要这个。 那么我如何返回一个 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
};
}
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
});
}
另一种可能性和@haim770答案的替代方案是带有 yield
关键字的循环:
在语句中使用 yield 关键字时,可以指示它出现的方法、运算符或 get 访问器是迭代器。使用 yield 定义迭代器,在为自定义集合类型实现 IEnumerable 和 IEnumerator 模式时,无需显式额外类(保存枚举状态的类,有关示例,请参阅 IEnumerator
)。
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;
因为它只是返回与db.tblAttachLabels
相同的集合。
其中
之一,具体取决于您是否喜欢 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
};
}
}