这是一个.cs页面,我有两个函数要执行,但错误是函数没有被执行,如果我评论一个函数,另一个将工作,两个都没有执行,它给出一个共同点错误object reference not set to an instance of an object
下面指定的是.cs页面。
Business bus = new Business();
try
{
intResult = bus.create_user(ua);
}
catch (Exception ex)
{
}
finally
{
bus = null;
}
int intres = 0;
try
{
intres = bus.fninsertuser_role_map(ua, role, i);
}
catch (Exception ee)
{
}
finally
{
bus = null;
}
数据访问对象
public int create_user(UserMaster ua)
{
// Connection connect = new Connection();
try
{
return cs.create_user(ua);
}
catch (Exception e)
{
throw e;
}
finally
{
cs = null;
}
}
public int fninsertuser_role_map(UserMaster ua, int[] role, int i)
{
// Connection connect = new Connection();
try
{
return cs.fninsertuser_role_map(ua, role, i);
}
catch (Exception e)
{
throw e;//**Throws the exception here.**
}
finally
{
//cs = null;
}
商业价值对象
public int create_user(UserMaster ua)
{
SqlConnection Con = new SqlConnection(str);
Con.Open();
SqlCommand Cmd = new SqlCommand("createuser", Con);
Cmd.CommandType = CommandType.StoredProcedure;
try
{
log.Debug("Inside Create user");
Cmd.Parameters.AddWithValue("@User_Id", ua.UserName);
Cmd.Parameters.AddWithValue("@Password", ua.Password);
Cmd.Parameters.AddWithValue("@Name", ua.Name);
Cmd.Parameters.AddWithValue("@Role_Id", ua.Role);
Cmd.Parameters.AddWithValue("@Department_Id", ua.Department);
Cmd.Parameters.AddWithValue("@Active", ua.Active);
log.Debug("Inside Create_User: New User created having ID: " + ua.UserName);
log.Info("user created");
return Cmd.ExecuteNonQuery();
}
catch (Exception e)
{
log.Debug("Error: Inside catch block of Create User");
log.Error("Error msg:" + e);
log.Error("Stack trace:" + e.StackTrace);
throw e;
}
finally
{
Cmd.Dispose();
Con.Close();
Con.Dispose();
}
}
/*Function to insert into user_role_map*/
public int fninsertuser_role_map(UserMaster u, int[] role, int i)
{
SqlConnection Con = new SqlConnection(str);
Con.Open();
transaction = Con.BeginTransaction();
int result = 0;
for (int a = 0; a < i; a++)
{
SqlCommand Cmd = new SqlCommand("create_UR_Map", Con, transaction);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Clear();
Cmd.Parameters.AddWithValue("@User_Id", u.UserName);
Cmd.Parameters.AddWithValue("@Role_Id", role[a]);
result = Cmd.ExecuteNonQuery();
}
transaction.Commit();
return result;
}
我只需要在同一页面中执行这两个功能。感谢任何帮助。
答案 0 :(得分:5)
问题:您正试图将null
放入实例变量bus
,然后使用相同的变量调用方法:
try
{
intResult = bus.create_user(ua);
}
catch (Exception ex)
{
}
finally
{
bus = null;//bus becomes null here for sure even if there is no excption thrown
}
int intres = 0;
try
{
intres = bus.fninsertuser_role_map(ua, role, i);//throws exception here
}
这就是它抛出object reference not set to an instance of an object
的原因。
注意:您应该记住finally
块将被执行,无论情况如何都意味着它将在所有情况下执行,并且您的实例变量bus
变为{{1即使没有抛出异常,也确定无法使用。
解决方案:我认为你需要真正重构你的代码,但你的意图是将实例变量null
变为bus
如果它抛出异常,如果是这种情况的话catch块中的那个语句。
试试这个:
null