LINQ对象引用未设置

时间:2012-10-18 14:45:02

标签: linq object reference

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

ctx是domaindatasource,我知道我试图删除的元素存在。

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

        }

3 个答案:

答案 0 :(得分:0)

我认为您的问题正在发生,因为您正在创建新的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);

然后使用if删除,如果它不是NULL

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

答案 1 :(得分:0)

在任何时候都是空的吗?

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

答案 2 :(得分:0)

重写您的代码如下:

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

 }