ASP/实体:数据库每次都为空



在 if 语句的末尾,busAddr始终是"不存在此类型的地址..."为了一切

为什么会这样?

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++;
}

看这一行

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

这将返回可查询对象。此时数据库查询尚未完成。因此,您需要以某种方式触发它,通过调用"ToList","First"或实际请求值的类似内容。

现在在这里

var address = gathered as tblbus_address;

您正在将此可查询强制转换为项类型。当然,此强制转换无效,因此该行的结果是null

要修复它,请强制 DB 查询并确保投射正确的内容。例如:

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;

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

并记住处理边缘情况,例如未找到项目。

最新更新