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

时间:2016-02-15 11:28:04

标签: asp.net entity-framework-4

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

1 个答案:

答案 0 :(得分:1)

看看这一行

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

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

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;

请记住处理边缘情况,例如找不到任何物品。