1

我正在开发 ASP.NET MVC3 应用程序。我想在我的服务中创建一个方法,该方法将仅返回具有我从调用该方法的位置提供的 id 的实体。

在我称为的服务中,DocumentService我编写了以下简单方法:

public Documents GetDocById(long id)
{
    return DocumentsRepository.All().Where(d => d.Id == id);
}

因为我只想要一个实体,所以我决定应该将方法的返回类型设置为被调用的实体的类型Documents。我使用此代码得到的错误是:

Cannot implicitly convert type "System.Linq.IQueryable<DataAccess.Documents> to DataAccess.Documents.

这是合乎逻辑的。但是想想我应该怎么做才能把它变成我想要的类型,我发现自己有问题。例如,我可以创建方法的返回类型,List<Documents>然后ToList()在我的 return 语句末尾添加。但我不期待一个列表,我期待一个记录而不是记录列表。

那么有没有办法,如果有的话,我怎样才能只返回一个实体而不是 List 与一个项目,这是我现在能想到的?

4

3 回答 3

2
return DocumentsRepository.All().SingleOrDefault(d => d.Id == id);

or

return DocumentsRepository.All().FirstOrDefault(d => d.Id == id);

if there are multiple entities with the same id.

于 2013-06-18T09:01:17.500 回答
1

You need this

public Documents GetDocById(long id)
{
    return DocumentsRepository.All().FirstOrDefault(d => d.Id == id);
}
于 2013-06-18T09:01:18.857 回答
1

Use FirstOrDefault:

return DocumentsRepository.All().Where(d => d.Id == id).FirstOrDefault();

This will return null if there is no document with the given Id.

于 2013-06-18T09:01:23.527 回答