entity-frameworkasp.net-core-webapi

ASP.NET Core Web API, EF, data from SQL stored procedure...: why the zero value is returned for the number of the record from result of the usp_proc?


I have an ASP.NET Core Web API endpoint, a SQL Server stored procedure is called to get the data.

Amongst the columns of the resulting DbSet<> the n is the counter with integer value (not NULL), and the mnozstvi (quantity) defined as numeric(19, 4), with NULL allowed.

The stored procedure is called like this:

public async Task<List<PolozkaKosiku>> GetAllAsync(string kodZakaznika)
{
    SqlParameter kodz = new SqlParameter("@kod_zakaznika", kodZakaznika);
    var polozkyKosiku = dbContext.Kosik
            .FromSql($"EXECUTE usp_kosik @kod_zakaznika={kodz}")
            .ToListAsync();

    return await polozkyKosiku;     
}

The PolozkaKosiku (BasketItem) defines the model

public class PolozkaKosiku
{
    [Column(TypeName = "int")]
    public int n { get; }

    [Column(TypeName = "numeric(19, 4)")]
    public decimal? Mnozstvi { get; set; }
}

There is also the related PolozkaKosikuDto class and the AutoMapper definition.

The Swagger UI shows the data were retrieved successfully

Swagger UI for the result

However, the n is always 0. When checking the results of calling the stored procedure the mnozstvi shows the expected values. The n correctly numbers the rows:

usp

I am stuck. Being new to ASP.NET Core Web API and EF, I do not know where to search for the bug.

One my guess is that it may be related to the modelBuilder. Earlier, the result was taken directly from the table. However, the stored procedures was introduced to enhance the records by related information, including the n as the order of the item. Also, the kosik table has the key ID, not the n (the n is not inside the table):

modelBuilder.Entity<PolozkaKosiku>()
    .ToTable("kosik")
    .HasKey(new string[] { "n" });

The n was declared as a key only to make the code working somehow.

Where is the bug?


Solution

  • The property n in class PolozkaKosiku has no setter. EF can't set the value for read only property.

    Modify your class

    public class PolozkaKosiku
    {
        [Column(TypeName = "int")]
        public int n { get; set; }