Share via


Los objetos valor no se pueden usar entre métodos en una consulta

Última modificación: viernes, 27 de mayo de 2011

Hace referencia a: SharePoint Foundation 2010

Disponible en SharePoint Online

Cuando se usa un método o propiedad para devolver un valor o un objeto que hereda de la clase ClientValueObject (JavaScript: ClientValueObject), no se puede usar el valor como parámetro para la llamada de otro método en la misma consulta. Para obtener más información sobre los objetos valor, vea Objetos de cliente, objetos valor y propiedades escalares.

Por ejemplo, imagine que desea crear una lista de SharePoint cuyo nombre para mostrar es el mismo que el título del sitio web. Si conoce el modelo de objetos de servidor de SharePoint Foundation, podría sentir la tentación de escribir código de la siguiente manera.

Incorrect Code

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class CreateList
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            Web oWebsite = clientContext.Web;

            ListCreationInformation listCreationInfo = new ListCreationInformation();
            listCreationInfo.TemplateType = 104;
            listCreationInfo.Title = oWebsite.Title;
            List oList = oWebsite.Lists.Add(listCreationInfo);

            clientContext.ExecuteQuery();
        }
    }
}

Al compilar el código, se devuelve una excepción PropertyOrFieldNotInitializedException porque "no se ha inicializado la propiedad o campo". El ejemplo devuelve una excepción porque la propiedad Title (JavaScript: title) del objeto de sitio web no está disponible antes de llamar a ExecuteQuery(). Mientras que SQL permite declarar una variable local que retiene el título del sitio web y permite usar la variable local para la creación de listas, no se puede declarar una variable local en el modelo de objetos de cliente. Por lo tanto, debe llamar a ExecuteQuery() o a ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)) dos veces; primero para devolver el valor de la propiedad Title (JavaScript: title) y luego para crear la lista, como se muestra en el siguiente ejemplo revisado.

Correct Code

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class CreateList
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            Web oWebsite = clientContext.Web;

            clientContext.Load(oWebsite, 
                w => w.Title);

            clientContext.ExecuteQuery();

            ListCreationInformation listCreationInfo = new ListCreationInformation();
            listCreationInfo.TemplateType = 104;
            listCreationInfo.Title = oWebsite.Title;
            List oList = oWebsite.Lists.Add(listCreationInfo);

            clientContext.ExecuteQuery();
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
   Class CreateList
      
      Shared Sub Main()
         Dim clientContext As New ClientContext("http://MyServer/sites/MySiteCollection")
         Dim oWebsite As Web = clientContext.Web
         
         clientContext.Load(oWebsite, Function(w) w.Title)
         
         clientContext.ExecuteQuery()
         
         Dim listCreationInfo As New ListCreationInformation()
         listCreationInfo.TemplateType = 104
         listCreationInfo.Title = oWebsite.Title
         Dim oList As List = oWebsite.Lists.Add(listCreationInfo)
         
         clientContext.ExecuteQuery()
      End Sub
   End Class
End Namespace
function getWebSiteTitle() {
    this.clientContext = new SP.ClientContext('/sites/TestWebs/TestWeb1');
    this.oWebsite = clientContext.get_web();

    clientContext.load(oWebsite, 'Title');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.createList), Function.createDelegate(this, this.onQueryFailed));    
}

function createList() {
    var listCreationInfo = new SP.ListCreationInformation();
    listCreationInfo.set_templateType(104);
    listCreationInfo.set_title(oWebsite.get_title());

    var oList = oWebsite.get_lists().add(listCreationInfo);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert('List created.');
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Vea también

Conceptos

Introducción a la recuperación de datos

Llamada a Load y ExecuteQuery antes de obtener acceso a las propiedades del valor

Los objetos de cliente pueden usarse en métodos en una consulta

Recuperación de datos de grupo en el mismo objeto

La recuperación de un objeto de cliente no recupera todas las propiedades