I am creating a Web API which will do CRUD operation. I have defined all the methods to CRUD but I am facing an issue when I try to update a data in db then either I had to pass all columns data else it is updating the columns with null and I want to do the null checking using ternary operator.
`Here is what I tried my code
In my DbContext class I have initialized all the parameters with null`
public bool UpdateEmployee(int empID, EmpModel emp)
{
SqlCommand cmd = new SqlCommand("Sp_UpdateEmployee", con);
cmd.CommandType= CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", empID);
cmd.Parameters.AddWithValue("@FirstName",emp.FirstName=null);
cmd.Parameters.AddWithValue("@LastName", emp.LastName=null);
cmd.Parameters.AddWithValue("@Gender", emp.Gender = null);
cmd.Parameters.AddWithValue("@Salary", emp.Salary=0);
cmd.Parameters.AddWithValue("@DeptId", emp.DeptId=0);
con.Open() ;
int i=cmd.ExecuteNonQuery();
con.Close();
if(i>=1) return true;
else return false;
}
In Controller class passing the updated id which is identical and the model class object.
[HttpPut]
public void Put(int id,EmpModel emp)
{
if (ModelState.IsValid == true)
db.UpdateEmployee(id,emp);
}
my stored procedure in sql server also I have given null checking and it is working fine in Sql server
ALTER PROCEDURE [dbo].[Sp_UpdateEmployee]
@ID int,
@FirstName varchar(100)=null,
@LastName varchar(50)=null,
@Gender varchar(20)=null,
@Salary bigint=null,
@DeptId int=null
AS
BEGIN
SET NOCOUNT ON;
update Employee set FirstName=Isnull(@FirstName,FirstName),LastName=Isnull(@LastName,LastName),
Gender=Isnull(@Gender,Gender),Salary=Isnull(@Salary,Salary),DeptId=Isnull(@DeptId,DeptId)
where ID=@ID
END
Here is the model class where I am getting the error
private string _firstname;
public string FirstName
{
get=> _firstname;
set=>FirstName=_firstname.ToString()==""? null:_firstname.ToString();
}
'In the model class where I am setting the property I am getting nullReferenceException which shows that I am passing null value but in database I have all the data present in the table so I am not getting why this exception is showing.'
set=>FirstName=_firstname.ToString()==""? null:_firstname.ToString();
I am getting error NullReferenceException Can anybody guide me where I am making mistake?