Search code examples
c#model-view-controllerasp.net-identitydbcontext

Null value on SQL statement include the result of a SELECT query on the row (show the SQL query you sent and the result from that query)


I am working on a project , in order to use the Identity features in the last steps, I had to make some changes on database and add Identity to it. Also, inherit DatabaContext from IdentityDbContext. In my previous method I used to make a new object of DatabaseContext and work on it :

private DatabaseContext db = new DatabaseContext();

But with the new changes, when I pass the model to View or apply a conditional input, it returns a null value, for example, the following code:

 public JsonResult CheckUserNameAvailability(Int32 UserCode)
    {
      
        var SearchData = db.Persons.Where(p => p.Pcode == UserCode).FirstOrDefault();////this line
        
        if (SearchData != null)
        {
            TempData["code"] = 0;

            return Json(1);
        }
        else
        {
            TempData["code"] = UserCode;
            return Json(0);
        }
    }

On the line

var SearchData = db.Persons.Where (p => p.Pcode == UserCode) .FirstOrDefault();

return Error

System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.

even though the database is not empty and this code used to work properly. If someone could provide some assistance, it would be terrific!

and This is Model:

namespace LeaveSheet.Models
{
    public class Person
    {
        [Key]
        public Int32 Id { get; set; }
        public Int32 Pcode { get; set; }
        public string Name { get; set; }
        public string Family { get; set; }
     }
}

codes in startup.cs

 public void ConfigureServices(IServiceCollection services)
    {        
        services.AddDbContext<DatabaseContext>(p => p.UseSqlServer(@"Data Source =. ; Initial Catalog = LeaveSheet; Integrated Security=True;MultipleActiveResultSets=true "));          
        services.AddControllersWithViews();
        services.AddIdentity<User, Role>().AddEntityFrameworkStores<DatabaseContext>().AddDefaultTokenProviders();
    }

Solution

  • Check whether the ID column in person table has always a value.

    Even though it is the key column in model, check whether it is same in DB as well.