-3

If my condition fails as rdr.HasRows == true, how can I respond my controller its fails

public Employee DeleteEmpById(int key)
{
    try
    {
        SqlCommand cmd = new SqlCommand("Sp_GetEmployeeById", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EmpId", key);
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows == true)
        {
        }
        else
        // Here what I mention when rdr.HasRows false
    }

Controller

public ActionResult DeleteById(int id)
{
    var x = ObjRepo.DeleteEmpById(id);
    return View(x);
}
Chandan Rauniyar
  • 814
  • 1
  • 14
  • 24
Md Ghousemohi
  • 197
  • 2
  • 13
  • 1
    What do you do when its `true`. And why does your method return an `Instance` of `Employee` (which makes no sense if its deleted)? And [Can we stop using AddWithValue() already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). And why is your method getting data when its name suggests it should be deleting data? –  Nov 26 '17 at 09:50
  • You could return `null` - or you could throw an exception ..... – marc_s Nov 26 '17 at 09:50
  • Please include the source code of `Sp_GetEmployeeById`. – mjwills Nov 26 '17 at 09:52
  • 1
    Side note: you should **not** use the `sp_` prefix for your stored procedures. Microsoft has [reserved that prefix for its own use (see *Naming Stored Procedures*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx), and you do run the risk of a name clash sometime in the future. [It's also bad for your stored procedure performance](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix). It's best to just simply avoid `sp_` and use something else as a prefix - or no prefix at all! – marc_s Nov 26 '17 at 11:38

1 Answers1

0

Use While Read

 Bool HasData =False ;
 SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
 {
    // If there is A row  sqlDataReader Will read 
    HasData  =true ;
    break; // you only have to check one time ,  performance improve


 }



return HasData
Floxy
  • 117
  • 2
  • 10
  • What in the world does this have to do with the question. –  Nov 27 '17 at 00:53
  • someone changed the question .simply he want to know , Retrieve data or not – Floxy Nov 27 '17 at 03:52
  • The only changes were to correct spelling errors and incorrect tags! `HasData` is a `bool` - OP methods returns `Employee` so this would just throw an exception! (in any case, the code in the question makes no sense) –  Nov 27 '17 at 03:54