Azure DocumentDb错误"查询必须评估为IEnumerable"

Ror*_*san 16 c# linq azure azure-cosmosdb

尝试检索单个记录时,我在尝试查询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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这种FindById方法会导致以下问题:

Microsoft.Azure.Documents.Client.dll中出现"Microsoft.Azure.Documents.Linq.DocumentQueryException"类型的异常,但未在用户代码中处理

附加信息:查询表达式无效,表达式返回类型
Foo.Models.DocumentDbEntities.UserDetail不受支持.查询必须评估为IEnumerable.

我不明白这个错误意味着什么,或者我如何解决它.我不希望返回一个IEnumerable或任何后代类,因为此方法将返回01记录.如果我删除该SingleOrDefault子句,并将返回类型更改为a IQueryable,它可以工作,但这不是我想要的.

Rya*_*our 30

SingleOrDefault() 在LINQ提供程序中不受支持.

将此更改为 .Where(u => u.Id.ToString() == id).AsEnumberable().FirstOrDefault();

  • 是否有任何关于Linq提供商支持Linq语句的文档? (6认同)
  • “AsEnumberable”中的拼写错误。它应该是“AsEnumerable”,作为一个懒惰的开发者,我在复制和粘贴时注意到了。 (2认同)