[英]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. 变量“ contact”的类型为
IQueryable<Contact>
, DeleteContact()
方法采用一个Contact对象。
How can I cast/convert contact from IQueryable<Contact>
into Contact
? 如何将联系人从
IQueryable<Contact>
转换/转换为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). 这是因为
Where
子句返回的是IQueryable<Contact>
(联系人的集合),而不是单个联系人(即使该集合中可能只有一个项目)。
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: 或者,如果只希望一个或一个都不希望,则可以使用
SingleOrDefault
来获取单个联系人:
var contact = repository.GetContacts.SingleOrDefault(p => p.ID == id);
// If it's not null, delete it
if (contact != null) repository.DeleteContact(contact);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.