Search code examples
asp.netentity-framework-4

ASP/Entity: Database is null every time


At the end of the if statement, the busAddr is always "No address for this type exists..." for everything

Why this might be?

int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
    queryID = busIDs[counter];
    var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c);
    var address = gathered as tblbus_address;
    var all = address.Address1;
    if (address != null && !string.IsNullOrEmpty(all[counter].ToString()))
    {
        string test = address.Address1[counter].ToString();
        busAddr.Add(test);
    }
    else
    {
        busAddr.Add("No address for this type exists...");
    }
    counter++;
}

Solution

  • Look at this line

    var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c);
    

    This returns a queryable. The DB query is not done yet at this point. So you need to trigger it somehow, by calling "ToList", "First" or similar thing that actually requests a value.

    Now here

    var address = gathered as tblbus_address;
    

    You are casting this queryable to a item type. Of course this cast is invalid, so the line results in null.

    To fix it, force the DB query and make sure you cast the right thing. For example:

    var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToList();
    var address = gathered[0] as tblbus_address;
    

    Or

    var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c);
    var address = gathered.First() as tblbus_address;
    

    And remember to deal with edge cases, such as no items found.