Home > OS >  Database query returning only the first element of the data base as the same instance for all, in AS
Database query returning only the first element of the data base as the same instance for all, in AS

Time:03-29

I am having some trouble and cannot figure out why my sql database is returning the first data entry as all the other entries.This is my method to get all the database table entries from the table called HealthDataFuture

[HttpPost]
        public IActionResult AjaxMethod(string id)
        {
            List<object> chartData = new List<object>();
            chartData.Add(new object[]
                            {
                            "Months", "SOFAS"
                            });
            //FOR SOME REASON IT KEEPS READING THE FIRST DATABASE ENTRY ONLY SO THERE ALL THE ENTRIES ARE THE SAME VALUE
            
            foreach (HealthDataFuture data in _db.HealthDataFuture)
            {
                if (data.id == id)
                {
                    chartData.Add(new object[]
                        {
                            data.Month, data.Sofas
                        });
                }
            }

            return Json(chartData);
        }

This is my model

This is my database table entries, it's returning the first entry as all the other ones when I query all of it, they have the same id because i want to return all of them and then graph

This is my database table entries, its returning the first entry as all the other ones too

This is the results i keep getting back

This is the results i keep getting back

i have also tried this way of getting data however it is the same problem

-------EDIT ----- PROBLEM RESOLVED It turns out my MYSQL table model was not created properly as there was no primary key nor foreign key

CodePudding user response:

It's better not to share image, but code using correct tag. To use code helps other users and all the cummunity, for example it makes your question searchable.

Anyway you can try to do in this way:

if (!string.IsNullOrEmpty(id)){
    List<HealthDataFuture> DataList = _db.HealthDataFuture.Where(x => h.Id == id).ToList();
    return View(id);
}
return RedirectToAction("Index");

I've also some question about your code:

  1. What should it do?
  2. DataList is like a select query from db, but nobody is using DataList. Why?

The more details you provide, the more information we have to help you.

Editing after comments:

If you want to remove data from db you should use saveChanges. For example, if you want to remove all lines with id other than "1", you can try:

if (!string.IsNullOrEmpty(id)){
    _db.HealthDataFuture.RemoveRange(_db.HealthDataFuture.Where(x => h.Id != id));
    _db.SaveChanges();
    return View(id);
}
return RedirectToAction("Index");

You can also read something about access to DB in async way, it's recommended and it perfoms better: https://docs.microsoft.com/it-it/ef/core/miscellaneous/async

  • Related