I am using ADO.NET Entity framework for connect db and get data. I want if there is no data in object it will write “EMPTY FIELD” if it’s full than it will write to listview coloumn data from the db. I am getting ‘System.NullReferenceException’ error when there is a null object in objectcontext.Dont return a ” EMPTY ROW” string.
Here is my code:
using (ITSEntities arama = new ITSEntities())
{
var sql = "SELECT VALUE s_tesis FROM ITSEntities.TB_SAGLIK_TESIS AS s_tesis WHERE s_tesis.TESIS_AD like @p1";
ObjectQuery<TB_SAGLIK_TESIS> sorgu = new ObjectQuery<TB_SAGLIK_TESIS>(sql, arama).Include("TB_IL").Include("TB_TESIS_TIPI").Include("TB_TESIS_TURU");
sorgu.Parameters.Add(new ObjectParameter("p1", String.Format("{0}%", btnAra.Text)));
listTesis.Items.Clear();
foreach (var item in sorgu)
{
ListViewItem listitem = new ListViewItem { Text = item.KODU.ToString() };
listitem.SubItems.Add(item.TESIS_AD);
listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_IL.ADI) ? "EMPTY ROW" : item.TB_IL.ADI);
listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TIPI.TIP_AD) ? "EMPTY ROW" : item.TB_TESIS_TIPI.TIP_AD);
listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TURU.TESIS_TURU) ? "EMPTY ROW" :item.TB_TESIS_TURU.TESIS_TURU);
listTesis.Items.Add(listitem);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
I don’t know EF, but you’re dereferencing 2 objects in the following lines:
If the container object (
KODU,TB_IL,TB_TESIS_TIPI. orTB_TESIS_TURU) is ever null, then you’d get a NullReferenceException.My guess is that these are table names, and that some rows don’t have a corresponding JOIN to those tables. In any case, you’d probably need to rewrite those as:
To make it a bit cleaner, a method: