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


C# DataServiceContext.UpdateObject方法代码示例

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


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

示例1: ClientSerializeGeographyTest_Update

 public void ClientSerializeGeographyTest_Update()
 {
     DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
     ctx.AttachTo("Entities", testEntity);
     ctx.UpdateObject(testEntity);
     ClientSerializeGeographyTest_Validate(ctx);
 }
开发者ID:larsenjo,项目名称:odata.net,代码行数:7,代码来源:SpatialTypeIntegrationTests.cs

示例2: 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

示例3: ApplyToObject

        /// <summary>
        /// Applies this state to the specfied <paramref name="target"/> such that after invocation, 
        /// the target in the given <paramref name="context"/> is in this state.
        /// </summary>
        /// <param name="context">Context to apply changes to.</param>
        /// <param name="target">Target to change state on.</param>
        /// <param name="entitySetName">Name of entity set (necessary for certain transitions).</param>
        public void ApplyToObject(DataServiceContext context, object target, string entitySetName)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            EntityStates current = GetStateForEntity(context, target);
            if (current == this.state)
            {
                return;
            }

            switch (this.state)
            {
                case EntityStates.Added:
                    if (current != EntityStates.Detached)
                    {
                        context.Detach(target);
                    }

                    context.AddObject(entitySetName, target);
                    break;
                case EntityStates.Detached:
                    context.Detach(target);
                    break;
                case EntityStates.Deleted:
                    if (current == EntityStates.Detached)
                    {
                        context.AttachTo(entitySetName, target);
                    }

                    context.DeleteObject(target);
                    break;
                case EntityStates.Modified:
                    if (current == EntityStates.Detached)
                    {
                        context.AttachTo(entitySetName, target);
                    }

                    context.UpdateObject(target);
                    break;
                case EntityStates.Unchanged:
                    if (current != EntityStates.Detached)
                    {
                        context.Detach(target);
                    }

                    context.AttachTo(entitySetName, target);
                    break;
            }
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:64,代码来源:EntityStateData.cs

示例4: CheckPassword

        private bool CheckPassword(DataServiceContext svc, string username, string password, bool updateLastLoginActivityDate, bool failIfNotApproved, out MembershipRow member)
        {
            bool createContextAndWriteState = false;
            try
            {
                if (svc == null)
                {
                    svc = this.CreateDataServiceContext();
                    createContextAndWriteState = true;
                }

                member = this.GetUserFromTable(svc, username);
                if (member == null)
                {
                    return false;
                }

                if (member.IsLockedOut)
                {
                    return false;
                }

                if (!member.IsApproved && failIfNotApproved)
                {
                    return false;
                }

                DateTime now = DateTime.UtcNow;
                string encodedPasswd = this.EncodePassword(password, member.PasswordFormat, member.PasswordSalt);

                bool isPasswordCorrect = member.Password.Equals(encodedPasswd);

                if (isPasswordCorrect && member.FailedPasswordAttemptCount == 0 && member.FailedPasswordAnswerAttemptCount == 0)
                {
                    if (createContextAndWriteState)
                    {
                        svc.UpdateObject(member);
                        svc.SaveChanges();
                    }

                    return true;
                }

                if (!isPasswordCorrect)
                {
                    if (now > member.FailedPasswordAttemptWindowStartUtc.Add(TimeSpan.FromMinutes(this.PasswordAttemptWindow)))
                    {
                        member.FailedPasswordAttemptWindowStartUtc = now;
                        member.FailedPasswordAttemptCount = 1;
                    }
                    else
                    {
                        member.FailedPasswordAttemptWindowStartUtc = now;
                        member.FailedPasswordAttemptCount++;
                    }

                    if (member.FailedPasswordAttemptCount >= this.MaxInvalidPasswordAttempts)
                    {
                        member.IsLockedOut = true;
                        member.LastLockoutDateUtc = now;
                    }
                }
                else
                {
                    if (member.FailedPasswordAttemptCount > 0 || member.FailedPasswordAnswerAttemptCount > 0)
                    {
                        member.FailedPasswordAnswerAttemptWindowStartUtc = ProvidersConfiguration.MinSupportedDateTime;
                        member.FailedPasswordAnswerAttemptCount = 0;
                        member.FailedPasswordAttemptWindowStartUtc = ProvidersConfiguration.MinSupportedDateTime;
                        member.FailedPasswordAttemptCount = 0;
                        member.LastLockoutDateUtc = ProvidersConfiguration.MinSupportedDateTime;
                    }
                }

                if (isPasswordCorrect && updateLastLoginActivityDate)
                {
                    member.LastActivityDateUtc = now;
                    member.LastLoginDateUtc = now;
                }

                if (createContextAndWriteState)
                {
                    svc.UpdateObject(member);
                    svc.SaveChanges();
                }

                return isPasswordCorrect;
            }
            catch (Exception e)
            {
                if (e.InnerException is DataServiceClientException && (e.InnerException as DataServiceClientException).StatusCode == (int)HttpStatusCode.PreconditionFailed)
                {
                    // this element was changed between read and writes
                    Log.Write(EventKind.Warning, "A membership element has been changed between read and writes.");
                    member = null;
                    return false;
                }
                else
                {
                    throw new ProviderException("Error accessing the data store!", e);
//.........这里部分代码省略.........
开发者ID:WindowsAzure-Toolkits,项目名称:wa-toolkit-wp-nugets,代码行数:101,代码来源:TableStorageMembershipProvider.cs

示例5: UpdateEntityAndSetSaveStream

        public void UpdateEntityAndSetSaveStream()
        {
            // Making sure that updating an entity followed by SetSaveStream works well
            TestUtil.RunCombinations(
                 UnitTestsUtil.BooleanValues,
                 (IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)),
                 UnitTestsUtil.BooleanValues,
                 (sendResponse, mode, closeStream) =>
                 {
                     using (PlaybackService.OverridingPlayback.Restore())
                     using (PlaybackService.InspectRequestPayload.Restore())
                     {
                         DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                         context.EnableAtom = true;
                         context.Format.UseAtom();

                         string payload = AtomParserTests.AnyEntry(
                                         id: Id,
                                         editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                         serverTypeName: typeof(Customer).FullName,
                                         properties: Properties,
                                         links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                         GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));

                         PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                         context.ResolveType = name => typeof(Customer);
                         Customer c = (Customer)context.Execute<object>(new Uri("/Customers(1)", UriKind.Relative)).Single();
                         context.UpdateObject(c);
                         MemoryStream thumbnailStream = new MemoryStream();
                         context.SetSaveStream(c, "Thumbnail", thumbnailStream, closeStream, new DataServiceRequestArgs() { ContentType = "image/bmp" });

                         string namedStreamETagInEntityResponse = null;
                         string namedStreamETagInResponseHeader = "ETagInResponseHeader";
                         int i = 0;
                         PlaybackService.InspectRequestPayload.Value = (message) =>
                         {
                             if (i == 1)
                             {
                                 // Verify the first request was a PUT request to the entity
                                 Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PATCH {0}/editLink/Customers(1)", request.ServiceRoot)), "the first request must be a PUT request to the entity");

                                 var headers = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("ETag", namedStreamETagInResponseHeader) };
                                 PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(headers, null);
                             }
                             else if (i == 0)
                             {
                                 string updatePayload = null;
                                 if (sendResponse)
                                 {
                                     namedStreamETagInEntityResponse = "ETagInResponsePayload";
                                     updatePayload = AtomParserTests.AnyEntry(
                                        id: Id,
                                        editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                        properties: Properties,
                                        links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                        GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: namedStreamETagInEntityResponse));
                                 }
                                 PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, updatePayload);

                                 // Verify the payload of the first request - it must have an entry element.
                                 XDocument document = XDocument.Load(message);
                                 Assert.IsTrue(document.Element(AstoriaUnitTests.Tests.UnitTestsUtil.AtomNamespace + "entry") != null, "must contain an entry element");
                             }

                             i++;
                             Assert.IsTrue(thumbnailStream.CanWrite, "The thumbnail stream hasn't been closed yet");
                         };

                         DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.None, mode);
                         Assert.AreEqual(i, 2, "Only 2 request should have been made");

                         // Verify that the second request was a PUT request
                         Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PUT {0}/Customers(1)/EditLink/Thumbnail", request.ServiceRoot)), "the second request must be a PUT request to named stream");

                         // If the first update sent a response, then the new etag must be used
                         Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("If-Match: {0}", namedStreamETagInEntityResponse ?? MediaETag)), "etag must be sent in the PUT request to the named stream");

                         Assert.AreEqual(!thumbnailStream.CanWrite, closeStream, "The thumbnail stream must be desired state after SaveChanges returns");

                         StreamDescriptor sd = context.Entities[0].StreamDescriptors[0];

                         // Verify that the etag from the response overrides the etag from the header when the response is present
                         Assert.AreEqual(sd.StreamLink.ETag, namedStreamETagInResponseHeader, "make sure the etag was updated to the latest etag");
                     }
                 });
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:86,代码来源:NamedStreamTests.cs

示例6: SetSaveStreamAndUpdateEntity

        public void SetSaveStreamAndUpdateEntity()
        {
            // Making sure that setting the save stream followed by updating an entity works well
            TestUtil.RunCombinations((IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)), (mode) =>
                {
                    using (PlaybackService.OverridingPlayback.Restore())
                    using (PlaybackService.InspectRequestPayload.Restore())
                    {
                        DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        context.EnableAtom = true;
                        context.Format.UseAtom();

                        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) +
                                        GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", MediaContentType));

                        PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                        Customer c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
                        PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, null);

                        context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true, new DataServiceRequestArgs() { ContentType = "image/bmp" });
                        context.UpdateObject(c);

                        int i = 0;
                        PlaybackService.InspectRequestPayload.Value = (message) =>
                        {
                            if (i == 1)
                            {
                                // Verify that the second request was a PUT request
                                Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PUT {0}/Customers(1)/EditLink/Thumbnail", request.ServiceRoot)), "the second request must be a PUT request to named stream");
                                Assert.IsTrue(!PlaybackService.LastPlayback.Contains(String.Format("If-Match", "no if-match header must be sent if the named stream does not have etag")));

                                // Verify the payload of the first request - it must have an entry element.
                                XDocument document = XDocument.Load(message);
                                Assert.IsTrue(document.Element(AstoriaUnitTests.Tests.UnitTestsUtil.AtomNamespace + "entry") != null, "must contain an entry element");
                            }

                            i++;
                        };

                        DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.ContinueOnError, mode);
                        Assert.AreEqual(i, 2, "Only 2 request should have been made");

                        // Verify the first request was a PUT request to the entity
                        Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PATCH {0}/editLink/Customers(1)", request.ServiceRoot)), "the first request must be a PUT request to the entity");
                    }
                });
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:51,代码来源:NamedStreamTests.cs

示例7: NamedStreams_PayloadDrivenMaterialization

        public void NamedStreams_PayloadDrivenMaterialization()
        {
            // Make sure DSSL properties can materialized and populated with the right url in non-projection cases
            {
                // Testing without projections (payload driven) and making sure one is able to project out the stream url
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                context.IgnoreMissingProperties = true;
                var q = context.CreateQuery<EntityWithStreamLink>("MySet1");
                object entity = null;

                foreach (EntityWithStreamLink o in q)
                {
                    Assert.IsNotNull(o.Stream1, "Stream1 must have some value");
                    Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the value in the entity descriptor must match with the property value");
                    Assert.IsNull(o.SomeRandomProperty, "SomeRandomProperty must be null, since the payload does not have the link with the property name");
                    entity = o;
                }

                // Try updating the entity and make sure that the link is not send back in the payload.
                context.UpdateObject(entity);

                WrappingStream wrappingStream = null;
                context.RegisterStreamCustomizer((inputStream) =>
                    {
                        wrappingStream = new WrappingStream(inputStream);
                        return wrappingStream;
                    },
                    null);

                try
                {
                    context.SaveChanges();
                    Assert.Fail("Save changes should throw an exception");
                }
                catch (Exception)
                {
                    // do nothing
                }

                string payload = wrappingStream.GetLoggingStreamAsString();
                Assert.IsTrue(payload.Contains("<d:ID m:type=\"Int32\">1</d:ID>"), "Id element must be present");
                Assert.IsFalse(payload.Contains("Stream1Url"), "link url should not be sent in the payload");
            }
        }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:46,代码来源:NamedStream_ProjectionTests.cs

示例8: Collection_Blobs

            public void Collection_Blobs()
            {
                DSPMetadata metadata = CreateMetadataForXFeatureEntity(true);

                DSPServiceDefinition service = new DSPServiceDefinition() { 
                    Metadata = metadata, 
                    Writable = true, 
                    SupportMediaResource = true,
                    MediaResourceStorage = new DSPMediaResourceStorage()
                };

                byte[] clientBlob = new byte[] { 0xcc, 0x10, 0x00, 0xff };

                DSPContext data = new DSPContext();
                service.CreateDataSource = (m) => { return data; };

                using (TestWebRequest request = service.CreateForInProcessWcf())
                using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                {
                    DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                    request.StartService();

                    XFeatureTestsMLE clientMle = new XFeatureTestsMLE() {
                        ID = 1,
                        Description = "Entity 1",
                        Strings = new List<string>(new string[] { "string 1", "string 2", string.Empty }),
                        Structs = new List<XFeatureTestsComplexType>(new XFeatureTestsComplexType[] {
                                    new XFeatureTestsComplexType() { Text = "text 1" },
                                    new XFeatureTestsComplexType() { Text = "text 2" }}) };


                    DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
                    ctx.EnableAtom = true;
                    ctx.Format.UseAtom();

                    ctx.AddObject("Entities", clientMle);
                    ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
                    ctx.SaveChanges();
                    VerifyMLEs(service, clientMle, clientBlob);

                    // Read stream and verify stream contents
                    using (Stream serverStream = ctx.GetReadStream(clientMle).Stream)
                    {
                        VerifyStream(clientBlob, serverStream);
                    }

                    // modify MLE and the corresponding stream 
                    clientMle.Structs.Add(new XFeatureTestsComplexType() { Text = "text 3" });
                    clientMle.Strings.RemoveAt(0);
                    clientBlob[0] ^= 0xff;
                    ctx.UpdateObject(clientMle);
                    ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
                    ctx.SaveChanges();
                    VerifyMLEs(service, clientMle, clientBlob);

                    // delete MLE
                    ctx.DeleteObject(clientMle);
                    ctx.SaveChanges();

                    Assert.IsNull((DSPResource)service.CurrentDataSource.GetResourceSetEntities("Entities").
                            FirstOrDefault(e => (int)(((DSPResource)e).GetValue("ID")) == (int)clientMle.GetType().GetProperty("ID").GetValue(clientMle, null)),
                            "MLE has not been deleted.");

                    Assert.AreEqual(0, service.MediaResourceStorage.Content.Count(), "The stream on the server has not been deleted.");
                };
            }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:66,代码来源:CollectionCrossFeature.cs

示例9: Collection_ChangeInterceptors

            public void Collection_ChangeInterceptors()
            {
                var metadata = CreateMetadataForXFeatureEntity();

                InterceptorServiceDefinition service = new InterceptorServiceDefinition()
                {
                    Metadata = metadata,
                    CreateDataSource = (m) => new DSPContext(),
                    Writable = true,
                    EnableChangeInterceptors = true
                };

                // client cases
                TestUtil.RunCombinations(new string[] { "POST", "PUT", "PATCH", "DELETE" }, new bool[] { false, true }, (httpMethod, batch) =>
                {
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.Accept = "application/atom+xml,application/xml";
                        request.StartService();

                        DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();

                        if (httpMethod != "POST")
                        {
                            service.EnableChangeInterceptors = false;
                            PopulateClientContextWithTestEntities(ctx);
                            service.EnableChangeInterceptors = true;
                        }

                        ctx.IgnoreResourceNotFoundException = true;

                        var resource = ctx.CreateQuery<XFeatureTestsEntity>("Entities").FirstOrDefault();
                        SaveChangesOptions saveOptions = batch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None;
                        switch (httpMethod)
                        {
                            case "POST":
                                resource = new XFeatureTestsEntity() { ID = 42, Strings = new List<string>(), Structs = new List<XFeatureTestsComplexType>() };
                                ctx.AddObject("Entities", resource);
                                break;
                            case "PUT":
                                saveOptions |= SaveChangesOptions.ReplaceOnUpdate;
                                ctx.UpdateObject(resource);
                                break;
                            case "PATCH":
                                ctx.UpdateObject(resource);
                                break;
                            case "DELETE":
                                ctx.DeleteObject(resource);
                                break;
                        }
                        ctx.SaveChanges(saveOptions);

                        Assert.AreEqual((int?)resource.ID, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
                        service.ChangeInterceptorCalledOnEntityId = null;
                    }
                });

                service.EnableChangeInterceptors = true;
                service.ChangeInterceptorCalledOnEntityId = null;

                // server cases (these operations can't be done using client API)
                TestUtil.RunCombinations(
                    new string[] { "Strings", "Structs" }, 
                    new string[] { UnitTestsUtil.MimeApplicationXml}, 
                    (collectionPropertyName, format) =>
                {
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.StartService();

                        DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        service.EnableChangeInterceptors = false;
                        PopulateClientContextWithTestEntities(ctx);
                        service.EnableChangeInterceptors = true;

                        // Get the collection property payload
                        var payload = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/Entities(1)/" + collectionPropertyName, format);

                        // And send a PUT with that payload back
                        request.HttpMethod = "PUT";
                        request.Accept = format;
                        request.RequestContentType = format;
                        request.RequestUriString = "/Entities(1)/" + collectionPropertyName;
                        request.SetRequestStreamAsText(payload.ToString());
                        request.SendRequest();

                        Assert.AreEqual((int?)1, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
                        service.ChangeInterceptorCalledOnEntityId = null;
                    }
                });
            }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:99,代码来源:CollectionCrossFeature.cs

示例10: Collection_BatchIDataServiceHostAndChangeTracking

            public void Collection_BatchIDataServiceHostAndChangeTracking()
            {
                DSPMetadata metadata = CreateMetadataForXFeatureEntity();

                TestUtil.RunCombinations(
                    new bool[] { false, true },
                    new bool[] { false, true },
                    new Type[] { typeof(IDataServiceHost), typeof(IDataServiceHost2) },
                    (sendAsBatch, replaceOnUpdate, hostInterfaceType) => {

                    DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, HostInterfaceType = hostInterfaceType };
                    
                    DSPContext data = new DSPContext();
                    service.CreateDataSource = (m) => { return data; };
                    // This test operates just on 2 entities - so let's take just first two from the set
                    List<object> testEntities = CreateClientTestEntities().Take(2).ToList<object>();
                    SaveChangesOptions saveOptions = 
                        (sendAsBatch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None) | 
                        (replaceOnUpdate ? SaveChangesOptions.ReplaceOnUpdate : SaveChangesOptions.None);

                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.StartService();

                        // Add entities
                        DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        foreach (XFeatureTestsEntity entity in testEntities)
                        {
                            ctx.AddObject("Entities", entity);
                        }
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Added);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Change one of the entities
                        ((XFeatureTestsEntity)testEntities[0]).Structs.RemoveAt(0);
                        ctx.UpdateObject(testEntities[0]);
                        VerifyStateOfEntities(ctx, new[] { testEntities[0] }, EntityStates.Modified);
                        VerifyStateOfEntities(ctx, new[] { testEntities[1] }, EntityStates.Unchanged);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Change collection in both entities
                        List<string> tempCollection = ((XFeatureTestsEntity)testEntities[0]).Strings;
                        ((XFeatureTestsEntity)testEntities[0]).Strings = ((XFeatureTestsEntity)testEntities[1]).Strings;
                        ((XFeatureTestsEntity)testEntities[1]).Strings = tempCollection;
                        ctx.UpdateObject(testEntities[0]);
                        ctx.UpdateObject(testEntities[1]);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Modified);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Delete entities
                        ctx.DeleteObject(testEntities[0]);
                        ctx.DeleteObject(testEntities[1]);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Deleted);
                        ctx.SaveChanges(saveOptions);
                        testEntities.RemoveAt(0);
                        testEntities.RemoveAt(0);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
                    }
                });
            }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:70,代码来源:CollectionCrossFeature.cs

示例11: TestLongTypeAsPrimaryKey

        public void TestLongTypeAsPrimaryKey()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri(this.BaseAddress));
            var models = ctx.CreateQuery<LongPrimaryKeyType>("LongPrimaryKeyType").ToList();

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

                ctx.UpdateObject(model);

                var response = ctx.SaveChanges().Single();

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


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