从.net调用DocumentDb存储过程

时间:2016-04-15 19:31:40

标签: c# azure stored-procedures azure-cosmosdb

我有以下存储过程,只能通过id找到一个对象。

function sample(id) {
    var context = getContext();
    var response = context.getResponse();
    var collection = context.getCollection();

    var findObject = "SELECT * FROM Objects o where o.userId='" + id +"'";

    // Query documents and take 1st item.
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        findObject,

        function (err, feed, options) {
            if (err) throw err;

            // Check the feed and if empty, set the body to 'no docs found', 
            // else take 1st element from feed
            if (!feed || !feed.length) throw new Error("Object not found");
            else response.setBody(feed[0]);
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

这是扩展Document

的C#类
public class UserPoints: Document
{
    [JsonProperty("userId")]
    public Guid UserId;

    [JsonProperty("remainingPoints")]
    public int RemainingPoints;
}

在我的main函数中,我调用上面的存储过程并期望它返回UserId的UserPoints对象。

例如:

UserPoints points = new UserPoints()
{
    UserId = Guid.NewGuid(),
    RemainingPoints = 1000
};

await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collection), points);
points.Dump();

var response = await client.ExecuteStoredProcedureAsync<UserPoints>(UriFactory.CreateStoredProcedureUri(databaseName, collection, storedProcedureName), points.UserId.ToString());
response.Response.Dump();

我收到以下异常执行存储过程时无法将“Microsoft.Azure.Documents.Document”类型的对象强制转换为“UserPoints”

如果我只是停止扩展Document基类,那么一切正常,但是我无法访问更新所需的SelfLink属性。难道我做错了什么?如果ExecuteStoredProcedureAsync采用强类型,它不应该能够键入强制类型并返回该类型的对象吗?

1 个答案:

答案 0 :(得分:0)

这是DocumentDB .NET SDK中的一个错误。我们正在调查修复程序。

请注意,作为修复程序发布之前的变通方法,您不必从Document派生到DocumentDB中存储文档。如果您需要访问某些内部属性(如ID),则可以将这些属性添加到对象中,例如如

 [JsonProperty("id")] public string Id {get; set;}