简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM