.NET Core Web API:如何用foreach向Data列表添加数据库数据
将数据库数据填充到Web API响应对象的实现方案
问题描述
我正在设计一个Web API,需要把数据库中所有Kullanicilar记录添加到DataResponse类的Data属性(List<Kullanicilar>类型)中。目前只能通过硬编码添加示例数据,不清楚如何用foreach逻辑实现从数据库读取并填充,相关类和当前控制器代码如下:
相关类定义
public partial class DataResponse { [JsonPropertyName("data")] public List<Kullanicilar> Data { get; set; } = null!; }
public partial class Kullanicilar { [JsonPropertyName("id")] public int KullaniciId { get; set; } [JsonPropertyName("ad_soyad")] public string AdSoyad { get; set; } = null!; [JsonPropertyName("il")] public string Il { get; set; } = null!; [JsonPropertyName("ilce")] public string Ilce { get; set; } = null!; [JsonPropertyName("eposta")] public string Eposta { get; set; } = null!; [JsonPropertyName("telefon")] public string Telefon { get; set; } = null!; [JsonPropertyName("kart")] public string Kart { get; set; } = null!; [JsonPropertyName("rfid")] public string Rfid { get; set; } = null!; [JsonPropertyName("durum")] public byte Durum { get; set; } }
当前控制器代码
public IActionResult Get() { var data = db.Kullanicilars.ToList(); var result = new DataResponse() { Data = new List<Kullanicilar>() { new Kullanicilar() { KullaniciId = 1, AdSoyad = "", Il = "", Ilce = "", Eposta = "", Telefon = "", Kart = "", Rfid = "", Durum = 1 }, } }; return Json(result); }
解决方案
你已经通过db.Kullanicilars.ToList()获取了数据库中的所有数据,以下两种方式可以实现将数据填充到DataResponse的Data属性中:
1. 直接赋值(高效简洁)
不需要手动遍历,因为ToList()返回的就是List<Kullanicilar>类型,可直接赋值给Data属性:
public IActionResult Get() { // 从数据库获取所有用户记录 var dbUserList = db.Kullanicilars.ToList(); // 直接将查询结果赋值给DataResponse的Data属性 var result = new DataResponse() { Data = dbUserList }; return Json(result); }
2. 使用foreach循环手动添加(满足指定逻辑需求)
如果必须用foreach遍历每条记录并添加到列表,可按以下方式实现:
public IActionResult Get() { var dbUserList = db.Kullanicilars.ToList(); var targetList = new List<Kullanicilar>(); // 遍历数据库返回的每条记录,添加到目标列表 foreach (var kullanici in dbUserList) { targetList.Add(kullanici); } var result = new DataResponse() { Data = targetList }; return Json(result); }
补充说明
- 第一种方式更高效,直接复用EF Core查询返回的列表,无需额外循环操作。
- 第二种方式完全符合你要求的
foreach逻辑,效果与直接赋值一致,仅多了手动遍历的步骤。 - 确保
db是已正确配置的数据库上下文实例,且实体映射与数据库表结构匹配。
内容的提问来源于stack exchange,提问作者onurkul
相关产品推荐
相关产品推荐

