I have a constructor like the one below that searches the DB for a company with the id and fills the object properties if the record is found. The problem is that if the record is not found the object is still created with empty properties. I want to change this so that if no company is found the object is not created at all.
Also, if a null value(for example) is returned when the company is not found how would I handle this from my calling code?
Any help would be great.
Cheers
public Company(int id)
{
try
{
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Company_Branch where BranchID = @BranchID",conn);
cmd.Connection = conn;
cmd.Parameters.Add(new SqlParameter("@BranchID",DbType.Int16));
cmd.Parameters["@BranchID"].Value = id;
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
//load object properties from data reader
}
conn.Close();
dr.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Throw an exception even if you don't find the row you are searching for... Catch the exception in the caller function and handle it there... And the just forget created object. It will be deleted by GC...
I would imagine that you may want to add a property to your class. Let's just call it "status". Within your constructor
set the value of the property based on the success or failure of trying to locate the id within your database. After creating an instance of your class within the calling code, immediately test the status property of your object. If it failed then you know which route to go in your calling code.
As for destroying the instance. C# garbage collection should handle your unused objects. However, I would imagine that
you are probably going to be using the same object reference for new instances of Company class. In that case the moment you declare a new company using the same object reference, the old will be immediately destroyed.
I never said my answer was the right one; just a different way to look at things.
Bookmarks