当前位置: 首页>>代码示例>>C#>>正文


C# DataServiceContext.CreateQuery方法代码示例

本文整理汇总了C#中DataServiceContext.CreateQuery方法的典型用法代码示例。如果您正苦于以下问题:C# DataServiceContext.CreateQuery方法的具体用法?C# DataServiceContext.CreateQuery怎么用?C# DataServiceContext.CreateQuery使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DataServiceContext的用法示例。


在下文中一共展示了DataServiceContext.CreateQuery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: NamedStreams_LoadPropertyTest

        //[TestMethod, Variation("One should not be able to get named streams via load property api")]
        public void NamedStreams_LoadPropertyTest()
        {
            // populate the context
            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
            EntityWithNamedStreams1 entity = context.CreateQuery<EntityWithNamedStreams1>("MySet1").Take(1).Single();

            try
            {
                context.LoadProperty(entity, "Stream1");
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }

            try
            {
                context.BeginLoadProperty(
                    entity,
                    "Stream1",
                    (result) => { context.EndLoadProperty(result); },
                    null);
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }
        }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:29,代码来源:NamedStream_ProjectionTests.cs

示例2: WhenOrdering_ThenSucceeds

	public void WhenOrdering_ThenSucceeds()
	{
		var config = HttpHostConfiguration.Create();
		config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", config))
		{
			var client = new HttpClient("http://localhost:20000");
			client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

			var context = new DataServiceContext(new Uri("http://localhost:20000"));
			// We always specify how many to take, to be explicit.
			var query = context.CreateQuery<Product>("products")
				.Where(x => x.Owner.Name == "kzu")
				.OrderBy(x => x.Id)
				.ThenBy(x => x.Owner.Id)
				.Skip(1)
				.Take(1);

			//var uri = ((DataServiceQuery)query).RequestUri;
			var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
			Console.WriteLine(uri);
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

			var products = new JsonSerializer().Deserialize<List<Product>>(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

			Assert.Equal(1, products.Count);
		}
	}
开发者ID:netfx,项目名称:extensions,代码行数:31,代码来源:HttpClientQuerySpec.cs

示例3: FilterCollectionWithAnyAll

        public void FilterCollectionWithAnyAll()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"), ODataProtocolVersion.V4);

            var values = ctx.CreateQuery<EntityWithCollections>("Values");
            var testCases = new[]
            {
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any()
                        select e,
                    url = "Values?$filter=CollectionOfInt/any()"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any() && e.ID == 0
                        select e,
                    url = "Values?$filter=CollectionOfInt/any() and ID eq 0"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any(mv => mv == 2 )
                        select e,
                    url = "Values?$filter=CollectionOfInt/any(mv:mv eq 2)"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any(mv => mv > e.ID ) && e.ID <100
                        select e,
                    url = "Values?$filter=CollectionOfInt/any(mv:mv gt $it/ID) and ID lt 100"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.Any(mv => e.CollectionOfString.All(s => s.StartsWith(mv.Name)) || e.ID <100) && e.ID > 50
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/any(mv:$it/CollectionOfString/all(s:startswith(s,mv/Name)) or $it/ID lt 100) and ID gt 50"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.All(mv => mv.Name.StartsWith("a") || e.ID <100) && e.ID > 50
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/all(mv:startswith(mv/Name,'a') or $it/ID lt 100) and ID gt 50"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.All(mv => mv.Name.Contains("a") || mv.Numbers.All(n=>n % 2 == 0)) && e.ID/5 == 3
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/all(mv:contains(mv/Name,'a') or mv/Numbers/all(n:n mod 2 eq 0)) and ID div 5 eq 3"
                },
            };

            TestUtil.RunCombinations(testCases, (testCase) =>
            {
                Assert.AreEqual(ctx.BaseUri.AbsoluteUri + testCase.url,testCase.q.ToString(), "url == q.ToString()");
            });
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:56,代码来源:LinqAnyAllTests.cs

示例4: NamedStreams_SimpleProjectionWithStreams

 public void NamedStreams_SimpleProjectionWithStreams()
 {
     // Doing projection of stream properties using AddQueryOption should work
     DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
     context.EnableAtom = true;
     context.Format.UseAtom();
     var query1 = context.CreateQuery<EntityWithNamedStreams1>("MySet1").AddQueryOption("$select", "ID, Stream1");
     List<EntityWithNamedStreams1> entities = query1.Execute().ToList();
     Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 1, "There must be named streams associated with the entity");
 }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:10,代码来源:NamedStream_ProjectionTests.cs

示例5: NamedStreams_SimpleProjectionWithoutStreams

 public void NamedStreams_SimpleProjectionWithoutStreams()
 {
     // Doing projection of non-stream properties should work and there should be no stream descriptors populated in the context
     DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
     context.EnableAtom = true;
     context.Format.UseAtom();
     var query1 = context.CreateQuery<EntityWithNamedStreams1>("MySet1").AddQueryOption("$select", "ID");
     List<EntityWithNamedStreams1> entities = query1.Execute().ToList();
     Assert.AreEqual(entities.Count, 1, "There must be only 1 entities populated in the context");
     Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 0, "There must be no named streams associated with the entity yet, since we didn't specify the named streams in the projection query");
 }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:11,代码来源:NamedStream_ProjectionTests.cs

示例6: ObterTodosProdutos

        public void ObterTodosProdutos()
        {
            string url = "http://localhost.fiddler:19523/Services/CatalogoDataService.svc";

            var context = new DataServiceContext(new Uri(url));

            var todosProdutos = context.CreateQuery<Produto>("Produtoes").ToList();

            foreach (var produto in todosProdutos)
            {
                Console.WriteLine(produto);
            }

            var produtosAcima100 = context.CreateQuery<Produto>("Produtoes").
                                        Where(p => p.Preco > 100).ToList();

            foreach (var produto in produtosAcima100)
            {
                Console.WriteLine(produto);
            }
        }
开发者ID:TiagoSoczek,项目名称:MOC,代码行数:21,代码来源:CatalogoDataServiceTestCase.cs

示例7: VerifyStreamInfoAfterQuery

        public void VerifyStreamInfoAfterQuery()
        {
            // Verifying media link information in query scnearios
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamEditLink(MediaEditLink, contentType: MediaContentType, etag: MediaETag) + GetNamedStreamSelfLink(MediaQueryLink, contentType: MediaContentType));

            string nonbatchPayload = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
            string batchPayload = PlaybackService.ConvertToBatchQueryResponsePayload(nonbatchPayload);

            TestUtil.RunCombinations((IEnumerable<QueryMode>)Enum.GetValues(typeof(QueryMode)), (queryMode) =>
            {
                using (PlaybackService.OverridingPlayback.Restore())
                {
                    if (queryMode == QueryMode.BatchAsyncExecute ||
                        queryMode == QueryMode.BatchAsyncExecuteWithCallback ||
                        queryMode == QueryMode.BatchExecute)
                    {
                        PlaybackService.OverridingPlayback.Value = batchPayload;
                    }
                    else
                    {
                        PlaybackService.OverridingPlayback.Value = nonbatchPayload;
                    }

                    DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    context.EnableAtom = true;
                    DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                    Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, queryMode)).Single();

                    Assert.AreEqual(context.Entities.Count, 1, "expecting just one entitydescriptor in the context");
                    Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 1, "expecting just one stream info in the entitydescriptor");
                    StreamDescriptor streamInfo = context.Entities[0].StreamDescriptors[0];
                    Assert.AreEqual(streamInfo.StreamLink.SelfLink, MediaQueryLink, "Self link should be as expected");
                    Assert.AreEqual(streamInfo.StreamLink.EditLink, MediaEditLink, "Edit link should be as expected");
                    Assert.AreEqual(streamInfo.StreamLink.ContentType, MediaContentType, "Content-Type did not match");
                    Assert.AreEqual(streamInfo.StreamLink.ETag, MediaETag, "ETag should match");
                }
            });
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:42,代码来源:NamedStreamTests.cs

示例8: TestLongTypeAsPrimaryKey

        public async Task TestLongTypeAsPrimaryKey()
        {
            var client = new DataServiceContext(new Uri(this.BaseAddress));
            client.Format.UseJson(GetEdmModel());

            var query = client.CreateQuery<LongPrimaryKeyType>("LongPrimaryKeyType");
            var models = await query.ExecuteAsync();

            foreach (var model in models)
            {
                Uri selfLink;
                Assert.True(client.TryGetUri(model, out selfLink));
                Console.WriteLine(selfLink);

                client.UpdateObject(model);

                var response = await client.SaveChangesAsync();

                Assert.Equal(200, response.Single().StatusCode);
            }
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:21,代码来源:SpecialPrimaryKeyTypesInLinkGenerationTests.cs

示例9: VerifyServerOrderId

        private void VerifyServerOrderId(int orderId, int? expectedCustomerId, String message = null)
        {
            var _ctx = new DataServiceContext(web.ServiceRoot);
            _ctx.EnableAtom = true;
            _ctx.Format.UseAtom();

            var order = _ctx.CreateQuery<EFFKClient.Order>("CustomObjectContext.Orders").Expand("Customers").Where(o => o.ID == orderId).FirstOrDefault();

            if (message == null)
            {
                message = String.Format("Order {0} expecting Customer {1}", orderId, expectedCustomerId);
            }

            Assert.IsNotNull(order, message);
            if (expectedCustomerId.HasValue)
            {
                Assert.AreEqual(expectedCustomerId, order.CustomerId, message);
                Assert.AreEqual(expectedCustomerId, order.Customers.ID, message);
            }
            else
            {
                Assert.IsNull(order.Customers);
            }
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:24,代码来源:Dev10EF4FKTests.cs

示例10: ResponseHeadersAndStreamTest

        public void ResponseHeadersAndStreamTest()
        {
            // Execute a query using a variety of methods (including sync, async, batch) and verify the response headers and payloads
            using (PlaybackService.OverridingPlayback.Restore())
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
            {
                request.ServiceType = typeof(PlaybackService);
                request.StartService();

                string nonbatchPayload =
@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>
<entry xml:base=""http://sparradevvm1:34866/TheTest/"" xmlns:d=""http://docs.oasis-open.org/odata/ns/data"" xmlns:m=""http://docs.oasis-open.org/odata/ns/metadata"" m:etag=""W/&quot;3d9e3978-e6a7-4742-a44e-ef5a43d18d5f&quot;"" xmlns=""http://www.w3.org/2005/Atom"">
  <id>http://sparradevvm1:34866/TheTest/Customers(1)</id>
  <title type=""text""></title>
  <updated>2010-10-12T18:07:17Z</updated>
  <author>
    <name />
  </author>
  <link rel=""edit"" title=""Customer"" href=""Customers(1)"" />
  <link rel=""http://docs.oasis-open.org/odata/ns/related/BestFriend"" type=""application/atom+xml;type=entry"" title=""BestFriend"" href=""Customers(1)/BestFriend"" />
  <link rel=""http://docs.oasis-open.org/odata/ns/related/Orders"" type=""application/atom+xml;type=feed"" title=""Orders"" href=""Customers(1)/Orders"" />
  <category term=""#AstoriaUnitTests.Stubs.CustomerWithBirthday"" scheme=""http://docs.oasis-open.org/odata/ns/scheme"" />
  <content type=""application/xml"">
    <m:properties>
      <d:GuidValue m:type=""Edm.Guid"">3d9e3978-e6a7-4742-a44e-ef5a43d18d5f</d:GuidValue>
      <d:ID m:type=""Edm.Int32"">1</d:ID>
      <d:Name>Customer 1</d:Name>
      <d:NameAsHtml>&lt;html&gt;&lt;body&gt;Customer 1&lt;/body&gt;&lt;/html&gt;</d:NameAsHtml>
      <d:Birthday m:type=""Edm.DateTimeOffset"">1980-10-12T00:00:00-07:00</d:Birthday>
      <d:Address m:type=""AstoriaUnitTests.Stubs.Address"">
        <d:StreetAddress>Line1</d:StreetAddress>
        <d:City>Redmond</d:City>
        <d:State>WA</d:State>
        <d:PostalCode>98052</d:PostalCode>
      </d:Address>
    </m:properties>
  </content>
</entry>
";
                string nonbatchHttpResponse = PlaybackService.ConvertToPlaybackServicePayload(null, nonbatchPayload);
                string batchPayload;
                string batchHttpResponse = PlaybackService.ConvertToBatchResponsePayload(new string[] { nonbatchHttpResponse }, true, out batchPayload);

                Dictionary<string, string> nonbatchHeaders = new Dictionary<string, string>();
                nonbatchHeaders.Add("Content-Type", "application/atom+xml");
                nonbatchHeaders.Add("__HttpStatusCode", "OK");
                nonbatchHeaders.Add("Content-Length", nonbatchPayload.Length.ToString());
                nonbatchHeaders.Add("Server", "Microsoft-HTTPAPI/2.0");
                nonbatchHeaders.Add("Date", null);

                Dictionary<string, string> batchHeaders = new Dictionary<string, string>();
                batchHeaders.Add("Content-Type", "multipart/mixed; boundary=batchresponse_e9b231d9-72ab-46ea-9613-c7e8f5ece46b");
                batchHeaders.Add("__HttpStatusCode", "Accepted");
                batchHeaders.Add("Content-Length", batchPayload.Length.ToString());
                batchHeaders.Add("Server", "Microsoft-HTTPAPI/2.0");
                batchHeaders.Add("Date", null);

                TestUtil.RunCombinations(((IEnumerable<QueryMode>)Enum.GetValues(typeof(QueryMode))), (queryMode) =>
                    {
                        Dictionary<string, string> expectedResponseHeaders;
                        string expectedResponsePayload;
                        bool isBatchQuery = queryMode == QueryMode.BatchAsyncExecute || queryMode == QueryMode.BatchAsyncExecuteWithCallback || queryMode == QueryMode.BatchExecute;
                        if (isBatchQuery)
                        {
                            PlaybackService.OverridingPlayback.Value = batchHttpResponse;
                            expectedResponseHeaders = batchHeaders;
                            expectedResponsePayload = batchPayload;
                        }
                        else
                        {
                            PlaybackService.OverridingPlayback.Value = nonbatchHttpResponse;
                            expectedResponseHeaders = nonbatchHeaders;
                            expectedResponsePayload = nonbatchPayload;
                        }

                        DataServiceContext context = new DataServiceContext(new Uri(request.BaseUri));
                        context.EnableAtom = true;
                        HttpTestHookConsumer testHookConsumer = new HttpTestHookConsumer(context, false);

                        DataServiceQuery<Customer> query = context.CreateQuery<Customer>("Customers");
                        foreach (var o in DataServiceContextTestUtil.ExecuteQuery(context, query, queryMode))
                        {
                        }

                        // Verify response headers
                        Assert.AreEqual(1, testHookConsumer.ResponseHeaders.Count, "Wrong number of response headers being tracked by the test hook.");
                        Dictionary<string, string> actualResponseHeaders = testHookConsumer.ResponseHeaders[0];
                        VerifyHeaders(expectedResponseHeaders, actualResponseHeaders);

                        // Verify response stream
                        Assert.AreEqual(1, testHookConsumer.ResponseWrappingStreams.Count, "Unexpected number of response streams tracked by the test hook.");
                        string actualResponsePayload = testHookConsumer.ResponseWrappingStreams[0].GetLoggingStreamAsString();
                        Assert.AreEqual(expectedResponsePayload, actualResponsePayload, "Response payload was not the value that was expected");

                        // Sanity check on the count of request streams, but not verifying them here. That functionality is tested more fully in another test method.
                        int expectedRequestStreamsCount = isBatchQuery ? 1 : 0;
                        Assert.AreEqual(expectedRequestStreamsCount, testHookConsumer.RequestWrappingStreams.Count, "Unexpected number of request streams.");
                    });
            }
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:100,代码来源:InternalTestHookTests.cs

示例11: NamedSteams_VerifyGetReadStreamVersion

        public void NamedSteams_VerifyGetReadStreamVersion()
        {
            // Verify that GetReadStream for a named stream sends version 3 headers
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                            id: Id,
                            editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                            properties: Properties,
                            links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType));

            TestUtil.RunCombinations(UnitTestsUtil.BooleanValues, (syncRead) =>
            {
                using (PlaybackService.OverridingPlayback.Restore())
                {
                    PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                    DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    context.EnableAtom = true;
                    DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                    Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();

                    if (syncRead)
                    {
                        context.GetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "img/jpeg" });
                    }
                    else
                    {
                        IAsyncResult result = context.BeginGetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "image/jpeg" }, (r) =>
                            {
                                context.EndGetReadStream(r);
                            },
                            null);

                        if (!result.CompletedSynchronously)
                        {
                            Assert.IsTrue(result.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, AstoriaUnitTests.TestConstants.MaxTestTimeout), false), "BeginExecute timeout");
                        }
                    }

                    VerifyRequestWasVersion3(PlaybackService.LastPlayback);
                }
            });
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:42,代码来源:NamedStreamTests.cs

示例12: GetUserInRole

        private RoleRow GetUserInRole(DataServiceContext svc, string rolename, string username)
        {
            SecUtility.CheckParameter(ref username, true, true, true, Constants.MaxTableUsernameLength, "username");
            SecUtility.CheckParameter(ref rolename, true, true, true, MaxTableRoleNameLength, "rolename");

            try
            {
                DataServiceQuery<RoleRow> queryObj = svc.CreateQuery<RoleRow>(_tableName);

                IEnumerable<RoleRow> query = from user in queryObj
                                             where user.PartitionKey == SecUtility.CombineToKey(_applicationName, username) &&
                                                   user.RowKey == SecUtility.Escape(rolename)
                                             select user;
                TableStorageDataServiceQuery<RoleRow> q = new TableStorageDataServiceQuery<RoleRow>(query as DataServiceQuery<RoleRow>, _tableRetry);
                try
                {
                    IEnumerable<RoleRow> userRows = q.ExecuteAllWithRetries();
                    return userRows.First();
                }
                catch (DataServiceQueryException e)
                {
                    HttpStatusCode s;
                    if (TableStorageHelpers.EvaluateException(e, out s) && s == HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }
开发者ID:wooboo,项目名称:lunchhunters,代码行数:37,代码来源:TableStorageRoleProvider.cs

示例13: GetSession

        private SessionRow GetSession(string id, DataServiceContext context)
        {
            Debug.Assert(context != null, "Http context is null");
            Debug.Assert(id != null && id.Length <= ProvidersConfiguration.MaxStringPropertySizeInChars, "Id is null or longer than allowed");

            try
            {
                DataServiceQuery<SessionRow> queryObj = context.CreateQuery<SessionRow>(this.tableName);
                var query = (from session in queryObj
                             where session.PartitionKey == SecUtility.CombineToKey(this.applicationName, id)
                             select session).AsTableServiceQuery();
                IEnumerable<SessionRow> sessions = query.Execute();

                // enumerate the result and store it in a list
                var sessionList = new List<SessionRow>(sessions);
                if (sessionList != null && sessionList.Count() == 1)
                {
                    return sessionList.First();
                }
                else if (sessionList != null && sessionList.Count() > 1)
                {
                    throw new ProviderException("Multiple sessions with the same name!");
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing storage.", e);
            }
        }
开发者ID:WindowsAzure-Toolkits,项目名称:wa-toolkit-wp-nugets,代码行数:33,代码来源:TableStorageSessionStateProvider.cs

示例14: CreateQuery

 private static DataServiceQuery<DataServicePackage> CreateQuery()
 {
     var dataServiceContext = new DataServiceContext(new Uri(NuGetOfficialFeedUrl));
     var query = dataServiceContext.CreateQuery<DataServicePackage>("Package");
     return query;
 }
开发者ID:Newtopian,项目名称:nuget,代码行数:6,代码来源:DataServiceQueryWrapperTest.cs

示例15: NamedStreams_Projections_MergeInfoOptions

        public void NamedStreams_Projections_MergeInfoOptions()
        {
            // Make sure that based on the MergeOption, the value of the DataServiceStreamLink is updated
            TestUtil.RunCombinations(
                    new EntityStates[] { EntityStates.Added, EntityStates.Deleted, EntityStates.Modified, EntityStates.Unchanged },
                    new MergeOption[] { MergeOption.AppendOnly, MergeOption.OverwriteChanges, MergeOption.PreserveChanges },
                    new int[] { -1, 0, 1 }, // -1 indicates less links, 0 means exact same number of links, 1 means some extra links
                    UnitTestsUtil.BooleanValues,
                    (entityState, mergeOption, extraLinks, useBatchMode) =>
                    {
                        using (PlaybackService.OverridingPlayback.Restore())
                        {
                            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                            context.EnableAtom = true;
                            context.Format.UseAtom();
                            context.MergeOption = mergeOption;

                            // Populate the context with a single customer instance with 2 named streams
                            string originalServiceRoot = "http://randomservice/Foo.svc";
                            string newServiceRoot = "http://randomservice1/Foo1.svc";

                            string payload = AtomParserTests.AnyEntry(
                                id: NamedStreamTests.Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: NamedStreamTests.Properties,
                                links: NamedStreamTests.GetNamedStreamEditLink(originalServiceRoot + "/Customers(1)/EditLink/Thumbnail"));

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                            DataServiceQuery<StreamType2> query = (DataServiceQuery<StreamType2>)context.CreateQuery<StreamType2>("Customers");

                            StreamType2 c = DataServiceContextTestUtil.CreateEntity<StreamType2>(context, "Customers", entityState, query);
                            PlaybackService.OverridingPlayback.Value = null;

                            string linksPayload = null;

                            if (extraLinks == -1)
                            {
                                // send no links
                            }
                            else if (extraLinks == 0)
                            {
                                linksPayload = NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail");
                            }
                            else
                            {
                                linksPayload = NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail") +
                                               NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Photo", name: "Photo");
                            }

                            payload = AtomParserTests.AnyEntry(
                                id: NamedStreamTests.Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: NamedStreamTests.Properties,
                                links: linksPayload);

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);

                            if (useBatchMode)
                            {
                                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToBatchQueryResponsePayload(PlaybackService.OverridingPlayback.Value);
                                QueryOperationResponse<StreamType2> resp = (QueryOperationResponse<StreamType2>)context.ExecuteBatch((DataServiceRequest)query).Single();
                                c = resp.First();
                            }
                            else
                            {
                                switch (extraLinks)
                                {
                                    case -1:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name
                                        }).Single();
                                        break;
                                    case 0:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name,
                                            Thumbnail = s.Thumbnail
                                        }).Single();
                                        break;
                                    default:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name,
                                            Thumbnail = s.Thumbnail,
                                            Photo = s.Photo
                                        }).Single();
                                        break;
                                }
                            }

                            EntityDescriptor entityDescriptor = context.Entities.Where(ed => Object.ReferenceEquals(c, ed.Entity)).Single();
                            StreamDescriptor thumbnail = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Thumbnail").SingleOrDefault();
                            //Assert.IsTrue(thumbnail == null || object.ReferenceEquals(thumbnail.EntityDescriptor, entityDescriptor), "StreamDescriptor.EntityDescriptor should point to the same instance of entity descriptor");
                            StreamDescriptor photo = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Photo").SingleOrDefault();
                            //Assert.IsTrue(photo == null || object.ReferenceEquals(photo.EntityDescriptor, entityDescriptor), "StreamDescriptor.EntityDescriptor should point to the same instance of entity descriptor for photo");

//.........这里部分代码省略.........
开发者ID:larsenjo,项目名称:odata.net,代码行数:101,代码来源:NamedStreamTests.cs


注:本文中的DataServiceContext.CreateQuery方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。