saturobi360
saturobi360

Reputation: 13

Getting Null value when there is no null in Database table

So what i am doing is that i am taking the response from a api endpoint, saving it to my DB table and then displaying the table contents.

I have gone through possible reasons as to why one can get a null value, as explained here http://www.sql-server-helper.com/error-messages/msg-515.aspx, and none of those reasons apply in this case.

For this particular table, i am getting a exception error,

An error occurred while updating the entries. See the inner exception for details.

Here is the exception message i get:

An error has occurred. Cannot insert the value NULL into column 'FrameSizeID', table 'diafirearmserver.dbo.Reference_Frame_Sizes'; column does not allow nulls. INSERT fails. The statement has been terminated. System.Data.SqlClient.SqlException at System.Data.SqlClient.SqlCommand.<>c.b__167_0(Task1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.d__0.MoveNext()

My Questions is: Why am i getting a null value being passed, when the table (Screenshot below) has no null values in it? What am i overlooking?

Here is a screenshot of the table that feeds the 'External api endpoint' Here is my data model:

namespace FirearmsAPI.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Reference_Frame_Sizes
    {
        public int FrameSizeID { get; set; }
        public string FrameSize { get; set; }
    }
}

Here is my Controller:

public class Reference_Frame_SizesController : ApiController
{
    private DataEntities db = new DataEntities();
    static string _address = "http://localhost:57454/api/Reference_Frame_Sizes?format=json";
    private List<Reference_Frame_Sizes> result;

    // GET: api/Reference_Frame_Sizes
    /// <summary>
    /// Retrieves Firearm Frame size data from external api endpoint, saves data to DB and returns Data
    /// </summary>
    public async Task<IEnumerable<Reference_Frame_Sizes>> GetReference_Frame_Sizes()
    {
        db.Database.ExecuteSqlCommand("TRUNCATE TABLE Reference_Frame_Sizes"); //Truncates internal table

        List<Reference_Frame_Sizes> resultset = await GetResponse();
        foreach (Reference_Frame_Sizes manu in resultset)
        {
            db.Reference_Frame_Sizes.Add(manu);
        }
        await db.SaveChangesAsync();
        return db.Reference_Frame_Sizes;
    }

    private async Task<List<Reference_Frame_Sizes>> GetResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        result = await response.Content.ReadAsAsync<List<Reference_Frame_Sizes>>();
        return result;
    }

protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool Reference_Frame_SizesExists(int id)
    {
        return db.Reference_Frame_Sizes.Count(e => e.FrameSizeID == id) > 0;
    }
}

Upvotes: 0

Views: 2066

Answers (2)

Igor
Igor

Reputation: 62268

The problem is with the EF mapping. The property FrameSizeID has the property StoreGeneratedPattern set to identity which means that EF will never try to provide a value at insert time. You need to remove that so that EF knows you will provide a value when you create a new record in the database. As EF does not provide a value and the value cannot be null this is generating the exception you are experiencing.

Solution Recap

Set the value of StoreGeneratedPattern to None for property FrameSizeID.

Supporting Documentation

Note

This is based on the latest comment that provided the following screen shot:

EF Properties for FrameSizeID

Upvotes: 1

You're not getting that error, because you're reading null values from the database, you're getting it because you're trying to insert null values into the database.

Use the debugger to evaluate the result of the GetResponse() method. odds are that one of the FrameSizeID properties is null.

Upvotes: 2

Related Questions