Matias Miraglio
Matias Miraglio

Reputation: 553

Can't cast IQueryable<Tobject> to Tobject

I have the following code

var contact = repository.GetContacts.Where(p => p.ID == id);
repository.DeleteContact(contact);

the variable "contact" is of type IQueryable<Contact>, the DeleteContact() method takes a Contact object.

How can I cast/convert contact from IQueryable<Contact> into Contact?

Upvotes: 0

Views: 58

Answers (1)

Rufus L
Rufus L

Reputation: 37020

That's because the Where clause is returning an IQueryable<Contact> (a collection of contacts), not a single contact (even though the collection may have only one item in it).

The two options that come to mind are either delete all of the contacts:

foreach (var contact in repository.GetContacts.Where(p => p.ID == id).ToList())
{
    repository.DeleteContact(contact);
}

Or if you only expect one or none, you can use SingleOrDefault to get a single contact:

var contact = repository.GetContacts.SingleOrDefault(p => p.ID == id);

// If it's not null, delete it
if (contact != null) repository.DeleteContact(contact);

Upvotes: 2

Related Questions