documentDB无法进行序列化存储过程响应或将其转换为我定义的类型



我的存储过程:(我通过Azure Script Explorer创建了它)

function GetAllResources() {
var collection = getContext().getCollection();
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
    collection.getSelfLink(),
    'SELECT * FROM MultiLanguage as m',
    function (err, docs, 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 (!docs || !docs.length) getContext().getResponse().setBody('no docs found');
        else getContext().getResponse().setBody(JSON.stringify(docs));
    });
    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

可以从Script Explorer成功执行Sproc。

我的C#代码致电Sproc:

 public async Task<IHttpActionResult>  GetReources() {
        client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
        var collectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
        //var docs = await client.ReadDocumentFeedAsync(collectionLink, new FeedOptions { MaxItemCount = 10 });

        //var docs = from d in client.CreateDocumentQuery<Models.Resource>(collectionLink)
        //           select d;
        StoredProcedure storedProcedure = client.CreateStoredProcedureQuery(collectionLink).Where(c => c.Id == "GetAllResources").AsEnumerable().FirstOrDefault();
        Models.Resource docs = await client.ExecuteStoredProcedureAsync<Models.Resource>(storedProcedure.SelfLink);

        foreach (var d in docs) {
            Models.Resource a = new Models.Resource();
            a = docs;
            //a.id = d.id;
            //a.Scenario = d.Scenario;
            //a.Translations = d.Translations;
            //a.LastModified = d.LastModified;
            //a.ModifiedBy = d.ModifiedBy;
            //a.LastAccessed = d.LastAccessed;
            resources.Add(a);
        }

        return Ok(resources);
    }

首先," foreach ..."有一个错误

foreach无法在类型模型的变量上操作。 不包含getEnumerator的公共定义。

然后,我尝试修改我的sproc以返回1结果并删除foreach行,然后我收到了错误,说

无法应对存储过程响应或将其转换为类型 'Models.Resource'

我只想将存储过程的结果作为我定义的类(Models.Resource)返回。如何做?

使用CreatestoredProcedureuri逐个名称可以更简单,例如:

        const string endpoint = "https://your.service.azure.com:443/";
        const string authKey = "<your magic secret master key>==";
        var client = new DocumentClient(new Uri(endpoint), authKey);
        Uri sprocUri = UriFactory.CreateStoredProcedureUri("databaseName", "collectionName", "GetAllResources");
        var result = await client.ExecuteStoredProcedureAsync<string>(sprocUri);

上面的存储过程序列化查询结果(DOCS数组)到字符串,如果您将其保留,则Sproc的结果将是字符串,我想您需要手动对象对象。您可以更简单地执行此操作,只需从sproc返回文档,并且结果作为对象(例如models.resource []),序列化将自动发生。

如果您将Sproc更改为仅返回一个文档(例如DO __.response.setBody(docs[0])和Models.Resource代表一个项目,则调用是正确的:

Models.Resource doc = await client.ExecuteStoredProcedureAsync<Models.Resource>(sprocUri);

另外,到//查询文档并获取第一项,我不建议使用脚本,因为脚本具有运行Javsscript引擎的开销。当您进行批量操作(以优化网络流量)或具有在服务器上运行有意义的业务逻辑时,脚本会启动。要采用第一项,您可以从客户端进行查询:从c选择顶部1 *。通常,您会在该子句中订购的位置。

例如,GitHub上有许多DOCDB样本,例如https://github.com/azure/azure-documentdb-dotnet/tree/master/master/samples/code-samples/code-samples/serversidecriptss和https and https and https://github。com/azure/azure-documentDB-dotnet/tree/master/samples/code-samples/queries。

谢谢,
迈克尔

好吧,让我们确保我们在同一页面上。

我正在使用与上面相同的sproc。我正在使用这样的客户码:

    class Models
    {
        // This would have more properties, I am just using id which all docs would have.
        public class Resource
        {
            [JsonProperty("id")]
            public string Id { get; set; }
        }
    }
    public async Task<IHttpActionResult> GetResources()
    {
        const string endpoint = "https://myservice.azure.com:443/";
        const string authKey = "my secret key==";
        var client = new DocumentClient(new Uri(endpoint), authKey);
        Uri sprocUri = UriFactory.CreateStoredProcedureUri("db", "c1", "GetAllResources");
        var serializedDocs = await client.ExecuteStoredProcedureAsync<string>(sprocUri);
        Models.Resource[] resources = JsonConvert.DeserializeObject<Models.Resource[]>(serializedDocs);
        return Ok(resources);
    }

它可以正常工作。这是你在做什么吗?

最新更新