I get a list of all users in my database with the following code:
IEnumerable<Firma> firmaer = db.Firma.ToList();
I try to map each user to a ViewModel that looks like this:
public class UserViewModel
{
public String CVR_Nummer { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime CreationDate { get; set; }
public String FirmaNavn { get; set; }
}
When the field firma_navn in the datbase is empty, i get a NullReferenceException
model.FirmaNavn = firmaer.Where(x => x.CVR_nummer == user.UserName).FirstOrDefault().firma_navn ?? "Missing";
It throws a NullReferenceException.
I can catch this exception, but i have heard somewhere that catching exceptions is kind of heavy.
What i would like to do is make
model.FirmaNavn = "Missing";
If the field is empty in the database.
Is this possible without catching the exception, or am i wrong about catching exception is heavy?
EDIT
This is how the method looks like now (after help):
public List<UserViewModel> MapUserViewModel(MembershipUserCollection users)
{
List<UserViewModel> userviewmodel = new List<UserViewModel>();
IEnumerable<Firma> firmaer = db.Firma.ToList();
foreach (MembershipUser user in users)
{
UserViewModel model = new UserViewModel();
model.CVR_Nummer = user.UserName;
model.CreationDate = user.CreationDate;
model.LastActivityDate = user.LastActivityDate;
var firma = firmaer.Where(x => x.CVR_nummer == user.UserName).FirstOrDefault();
if (firma != null)
{
if(string.IsNullOrEmpty(firma.firma_navn))
model.FirmaNavn = "Missing";
else
model.FirmaNavn = firma.firma_navn;
}
/*if (firmaer != null)
{
var firma = firmaer.Where(x => x.CVR_nummer == user.UserName).FirstOrDefault();
model.FirmaNavn = firma.firma_navn ?? "Mangler";
}
*/
userviewmodel.Add(model);
}
return userviewmodel;
}
Now works. Thanks.
You are not wrong about catching exceptions being “heavy” – and they should really only be used for the truly exceptional circumstances.
If
firma_navnis likely to benullthen it’s not an exceptional circumstance, so you should code accordingly: