【问题标题】:ASP/Entity: Database is null every timeASP/Entity:数据库每次都为空
【发布时间】:2018-04-15 21:19:55
【问题描述】:

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

【问题讨论】:

    标签: asp.net entity-framework-4


    【解决方案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;
    

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

    【讨论】:

    • 非常有用,我使用了FirstorDefault(); & 似乎已经修复了它。我还删除了索引中的计数器,因为我只希望查询中的第一个值。谢谢@Andrei(生病标记答案,必须再等7分钟才能这样做)。
    • ` if (address != null && !string.IsNullOrEmpty(address.Address1)) { var all = address.Address1;` 也必须解决这个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    相关资源
    最近更新 更多