【问题标题】:LINQ Object Referance not set未设置 LINQ 对象引用
【发布时间】:2012-10-18 14:45:02
【问题描述】:

在搜索从数据网格中选择的项目(在 Guid 上)时,我收到“对象引用未设置为对象的实例”错误。我已经检查过该项目是否正确返回了 Guid(通过将其写入页面上的标签),但是在我的 linq 查询中(我假设)我比较不正确。

ctx 是域数据源,我知道我试图删除的元素存在。

      private void medItemRemove_Click(object sender, RoutedEventArgs e)
    {

            MedicineInventory M = (MedicineInventory)medicineInventoryDataGrid.SelectedItem;
            Guid Mid = M.MedicineInventoryId;
            MedicineInventory toRemove = new MedicineInventory();
            toRemove = (from a in ctx.MedicineInventories where (a.MedicineInventoryId == Mid) select a).Single();
            ctx.MedicineInventories.Remove(toRemove);
            ctx.SubmitChanges();

        }

【问题讨论】:

  • 你能指定代码在哪一行中断吗?

标签: linq object reference


【解决方案1】:

重写你的代码如下:

private void medItemRemove_Click(object sender, RoutedEventArgs e)
{

    MedicineInventory M = (MedicineInventory)medicineInventoryDataGrid.SelectedItem;
    Guid Mid = M.MedicineInventoryId;
    MedicineInventory toRemove = (from a in ctx.MedicineInventories where (a != null && a.MedicineInventoryId == Mid) select a).SingleOrDefault();
    if (toRemove != null){
       ctx.MedicineInventories.Remove(toRemove);
       ctx.SubmitChanges();
    }
    else { .... } // code if toRemove is null

 }

【讨论】:

  • 我现在收到“序列不包含元素”错误...虽然我知道数据网格中的元素确实存在。
  • 我进行了编辑,您可以使用SingleOrDefault。如果未找到该行,则返回 null。
【解决方案2】:

在任何时候都为空吗?

toRemove = (from a in ctx.MedicineInventories where (a != null && a.MedicineInventoryId == Mid) select a).Single();

【讨论】:

    【解决方案3】:

    我认为您的问题正在发生,因为您正在创建一个新的MedicineInventory

    替换这个:

    MedicineInventory toRemove = new MedicineInventory();
    

    有了这个:

    var toRemove = ctx.MedicineInventories.Single(mi => mi.MedicineInventoryId == Mid);
    

    更新:

    当它返回错误消息“序列不包含元素”时,这是因为 EF 无法在数据库中找到具有您在 where 子句中使用的相同 Guid 的行。在这种情况下,为了避免异常,你可以试试这行代码:

    var toRemove = ctx.MedicineInventories.SingleOrDefault(
                                                      mi => mi.MedicineInventoryId == Mid);
    

    如果不是NULL,则使用if 删除:

    if(toRemove != null)
    {
        ctx.MedicineInventories.Remove(toRemove);
    
        ctx.SubmitChanges();
    }
    else
    {
        // Only you know what to do! :-)
    }
    

    SingleOrDefault 返回序列的唯一元素,或默认值 如果序列为空,则值(在这种情况下为NULL);这种方法 如果序列中有多个元素,则抛出异常。


    注意:您比较 Guid 的方式是正确的,因为 == 在 Guid 上重载,因此您不需要比较字符串表示形式。

    http://msdn.microsoft.com/en-us/library/system.guid.op_equality%28v=vs.110%29.aspx#Y474

    【讨论】:

    • 你确定你在数据库中的表有一个MedicineInventory,它和你在查询中传递的Guid相同吗?在我在回答中提到的代码行中放置一个断点,并记下 Guid 并将其与数据库端的那个进行比较。
    • 我是的。他们都有相同的Guid。是否有一些我需要更改阻止删除的元数据?
    • 我不知道...如果两者都是 Guid,则 LINQ 查询应该毫无问题地返回该单行,前提是 Guid 确实相同。确保与上下文 ctx 相关的连接字符串也指向正确的数据库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多