EFCore某张表中获取某几个字段
目录
1.背景
在前后端分离的应用场景中,某张统计表有20几个字段,但是前端可能只用到4个字段,这样就涉及到获取某个表中的部分字段值。本文介绍3种方法。
2.法一:linq
2.1 使用Select方法
List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表
int[] empIds = emplayeeList.Select(a => a.Id).ToArray(); //获取员工编号数组
2.2 使用ForEach方法
List<Emplayee> emplayeeList = GetEmplayeeList(); //获取员工信息列表
string empIds = "";
emplayeeList.ForEach(a => empIds += a.Id + ",");
empIds = empIds.TrimEnd(',');
Console.WriteLine(empIds); //输出:1,2,3
2.3 其他参考代码
/// <summary>
/// 员工信息类
/// </summary>
public class Emplayee
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 获取员工信息列表
/// </summary>
/// <returns></returns>
public static List<Emplayee> GetEmplayeeList()
{
List<Emplayee> emplayeeList = new List<Emplayee>();
Emplayee emplayee1 = new Emplayee() { Id = 1, Name = "张三" };
Emplayee emplayee2 = new Emplayee() { Id = 2, Name = "李四" };
Emplayee emplayee3 = new Emplayee() { Id = 3, Name = "王五" };
emplayeeList.Add(emplayee1);
emplayeeList.Add(emplayee2);
emplayeeList.Add(emplayee3);
return emplayeeList;
}
3.法二:IQueryble
3.1 参考例子一
我有个新闻表
id,title,body,createtime,author,click
使用ef4.1 仅仅读取 id,title,createtime 并显示在页面上。
public static List<NewInfo> GetHotNews()
{
List<NewInfo> list;
list = (from n in db.NewInfoes
where n.IsTop == 1
orderby n.PublishTime descending
select new
{
Title = n.Title,
NewID = n.NewID,
PublishTime = n.PublishTime
}).ToList();
return list;
}
改为
public static List<NewInfo> GetHotNews()
{
List<NewInfo> list;
list = (from n in db.NewInfoes
where n.IsTop == 1
orderby n.PublishTime descending
.Select(n => new NewInfo
{
Title = n.Title,
NewID = n.NewID,
PublishTime = n.PublishTime
});
return list;
}
备注:只是IEnumerable是把所有数据拉到内存里筛选,IQueryable会形成sql直接在库里查询返回
3.2 参考例子二
4.法三:建立一个对象,然后配置一个automapper,然后将查询结果匹配过来
具体可以自行尝试
参考:
1.网友 Kawhi(1585955375), 奥特曼迪斯特洛夫斯基(479663032)
2.https://blog.csdn.net/lcnmdfx/article/details/8332401
3.https://blog.csdn.net/pan_junbiao/article/details/51757904