LINQ Object Referance not set


I am getting an "Object Reference not set to an instance of an object" error when searching for an item (on Guid) that is selected from a datagrid. I have checked that the item does return the Guid correctly (by writing it to a label on the page), however in my linq query (i assume) i am comparing incorrectly.

ctx is the domaindatasource, I know the element im trying to remove exists.

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


Rewrite your code as follows:

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 }


Is a null at any point?

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


I think your problem is happening because you're creating a new MedicineInventory.

Replace this:

MedicineInventory toRemove = new MedicineInventory();

With this:

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


When it retuns the error message <em>"Sequence contains no elements"</em> it's because EF could not find a row in the database with the same Guid you're using in the where clause. In this case and to avoid an exception, you can try this line of code:

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

then use an if to delete if it's not NULL:

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

<a href="http://msdn.microsoft.com/en-us/library/bb342451.aspx" rel="nofollow">SingleOrDefault</a> returns the only element of a sequence, or a default value (NULL in this case) if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

</blockquote> <hr />

Note: the way you're comparing the Guids is correct because == is overloaded on Guid so you don't need to compare the string representations.

See <a href="http://msdn.microsoft.com/en-us/library/system.guid.op_equality%28v=vs.110%29.aspx#Y474" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.guid.op_equality%28v=vs.110%29.aspx#Y474</a>


  • Unable to copy text to clipboard while bound
  • Silverlight ComboBox binding with value converter
  • DropDownList not firing OnSelectedIndexChanged
  • After deleting a row , it just do not vanishes from the screen
  • WPF Style BasedOn does not work
  • UpdateSourceTrigger button click Converter
  • Shifting nodes up and down in a TreeView
  • How to correctly handle the CollectionChanged event of datagrid?
  • C# Error 'Object Reference Not Set To An Instance Of An Object'
  • Outlook Application.FileDialog not found
  • WPF context menu whose items are defined as data templates
  • Creating an object in Swift using the Objective-C factory method gives a compiler error [duplicate]
  • silverlight, ListBox navigation to new page with object possible?
  • Bind SelectedItem in a ListBox to CommandParameter in a ContextMenu
  • Trouble passing new object back to main form - C# .NET
  • Empty response from National Weather Service web service
  • process.kill() method doesn't work on windows 7
  • Get the ListBox row object from a button that is on the DataTemplate
  • How can i receive a reference to a control in WPF (MVVM)?
  • Search in A ListBox
  • WPF View ListView Backwards
  • c# system.net.dns universal app (W10) not working
  • Is it a good practice to use static classes to making the UI elements accessible from all the classe
  • ComboBox's SelectedItem is unexpectedly set to null before actual value
  • Change the Effect of Button once it is clicked WPF
  • C# InvokeRequired with property getter
  • Enable text box based on radio button selected
  • DataGrid: Help accessing a control defined in a CellEditingTemplate
  • Change Font Style (bold, Italic, bold italic) in C# [duplicate]
  • Add items to ComboBox at runtime?
  • Binding a list with another list with WPF
  • Share two different things in Windows Phone 8.1 C#
  • Unique SMS sender id?
  • UIBarButtonItem's action is not called when in a view with a UIGestureRecognizer
  • Exception HRESULT: 0x800455BC in speech recognition in Windows phone 8
  • How to access recipient on sent messages page with mailboxer
  • Click on button in another program - FindWindow, C#
  • c# open webrowser in many tab
  • How to Cache Real-time Data?
  • AT Commands to Send SMS not working in Windows 8.1