I'm designing a web api and I'm trying to add the fields you can see in the following class inside an object named Data.
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; }
}
But I don't know how to add every data from database to these list elements. I want to add items to the users list under the data object. I want every record to be saved in this list with a foreach logic.
My Controller Code:
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);
}
}
.net core list problem
CodePudding user response:
you can run a loop and add each item to the list like this.
var result = new DataResponse();
result.Data = new List<Kullanicilar>();
foreach (var item data)
{
result.Data.Add(new Kullanicilar()
{
KullaniciId = item.KullaniciId,
AdSoyad = item.AdSoyad,
Il = item.Il,
Ilce = item.Ilce,
Eposta = item.Eposta,
Telefon = item.Telefon,
Kart = item.Kart,
Rfid = item.Rfid,
Durum = item.Durum
});
}
return Json(result);