尝试检索单个记录时,我在尝试查询Azure DocumentDb存储帐户时遇到问题 . 这是我的WebAPI代码:
// Controller...
public AccountController : ApiController {
// other actions...
[HttpGet]
[Route("Profile")]
public HttpResponseMessage Profile()
{
var userId = User.Identity.GetUserId();
var rep = new DocumentRepository<UserDetail>();
var profile = rep.FindById(userId);
if (profile == null)
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Profile not found");
return Request.CreateResponse(HttpStatusCode.OK, profile);
}
}
// Repository
public class DocumentRepository<TEntity> : IDocumentRepository<TEntity> where TEntity : IIdentifiableEntity
{
private static DocumentClient _client;
private static string _databaseName;
private static string _documentsLink;
private static string _selfLink;
public DocumentRepository()
{
_client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentDbEndpointUrl"]), ConfigurationManager.AppSettings["DocumentDbAuthKey"]);
_databaseName = ConfigurationManager.AppSettings["DocumentDbDatabaseName"];
var _database = ReadOrCreateDatabase();
var collection = InitialiseCollection(_database.SelfLink, EntityName);
_documentsLink = collection.DocumentsLink;
_selfLink = collection.SelfLink;
}
// other methods...
public TEntity FindById(string id)
{
return _client.CreateDocumentQuery<TEntity>(_documentsLink).SingleOrDefault(u => u.Id.ToString() == id);
}
}
这是 FindById
方法导致以下问题:
Microsoft.Azure.Documents.Client.dll中出现“Microsoft.Azure.Documents.Linq.DocumentQueryException”类型的异常,但未在用户代码中处理其他信息:查询表达式无效,表达式返回类型Foo.Models.DocumentDbEntities .UserDetail不受支持 . 查询必须评估为IEnumerable .
我希望返回 IEnumerable
或任何后代类,因为此方法将返回 0
或 1
条记录 . 如果我删除 SingleOrDefault
子句,并将返回类型更改为 IQueryable
,它可以工作,但这不是我想要的 .
2 回答
在LINQ提供程序中不支持
SingleOrDefault()
.将此更改为
.Where(u => u.Id.ToString() == id).AsEnumberable().FirstOrDefault();
我不能说为什么Ryan的语法停止为你工作,但是你应该能够通过使用带有显式定义的查询字符串而不是使用.Where()的CreateDocumentQuery <>()重载来解决它而不会产生额外的性能 . :
您可能需要稍微使用查询,但该形式的某些内容应该起作用 .