Shoot me if this has been covered in the book or on this forum. Or for that matter if I am missing something simple!
With that out of the way. I have always wondered how to check for a object not existing in the database. Normally I would do it like this.
if(obj != null){
//use object
}
An example would be a ReadOnlyObject with a Factory method that takes in an ID.
If that id does not exist in the database the data portal will still create an instance of the object in its default state.
How would one go about checking for this?
How I have 'Solved' this in the past is to check a property to make sure it is not in its default state.
However this does not seem very clean. It wood be pretty odd to someone who did not know the subtle things in this framework...
Thanks,
PD
This is a common question. As I show in the book, exceptions are the most common way to know that data is not found. The DataPortal_Fetch() method simply doesn't catch exceptions, so they flow back to the client - to the UI typically. The reason is that the exception contains valuable information about WHY the object wasn't returned - because it could be missing data, but it could be that the database is down or an authorization violation or other reasons.
If you still want to do the obj!=null check, you can catch the exception in your factory method and just return null:
public static Customer GetCustomer(int id)
{
try {
return DataPortal.Fetch<Customer>(new Criteria(id));
}
catch {
return null;
}
}
Of course this approach means you lose the valuable exception detail, so it isn't an approach I typically use - but it works just fine.
Hey Guys,
Thanks for the reply. However I fear I was not clear about my use case.
I have a user control that displays some product data from a ReadOnly object that represents the product.See Code below.
int id = int.Parse(Request.QueryString["ProductId"]);
Product product = Product.GetProductByProductId(id);
if(product == null){
throw new ArgumentException("Invaild ID Parameter");
}
else{
//Bind data to controls
}
As you can see I want a to throw an exception if the a user puts an invalid product id into the query string. If I do not do this the attempt to bind the 'Empty' object will result in problems as the data bind happens.
Hope this clears up the problem as simple as it is.
PD
Lightbulb
Thanks,
PD
Copyright (c) Marimer LLC