ASP/Entity: 数据库每次都为空

ASP/Entity: Database is null every time

在 if 语句的末尾,busAddr 对于所有内容总是 "No address for this type exists..."

为什么会这样?

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);

这个returns一个可查询的。此时数据库查询尚未完成。所以你需要以某种方式触发它,通过调用 "ToList"、"First" 或类似的实际请求值的东西。

现在这里

var address = gathered as tblbus_address;

您正在将此可查询对象转换为项目类型。当然这个转换是无效的,所以该行结果为 null.

要修复它,请强制执行数据库查询并确保您输入正确的内容。例如:

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;

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