如何在 c# dot net 中使用三元运算符在不中断数据库表的所有其他数据的情况下更新现有数据

How to update an existing data without interrupting all other data of a database table using ternary operator in c# dot net

提问人:Sumana 提问时间:3/30/2023 最后编辑:Sumana 更新时间:3/30/2023 访问量:28

问:

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.

'这是我尝试的代码

在我的 DbContext 类中,我用 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();
        }
    



'在我设置属性的模型类中,我得到了nullReferenceException,这表明我正在传递null值,但在数据库中,我拥有表中存在的所有数据,所以我不明白为什么会出现此异常。


    set=>FirstName=_firstname.ToString()==""? null:_firstname.ToString();



I am getting error NullReferenceException Can anybody guide me where I am making mistake?

sql-update asp.net-core-webapi nullreferenceexception 条件运算符 null-check

评论


答: 暂无答案