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


C# DataServiceContext.DeleteObject方法代码示例

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


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

示例1: ExecuteAssetDeleteRequest

 private static Uri ExecuteAssetDeleteRequest( AssetDeleteOptionsRequestAdapter adapter)
 {
     Uri uri = null;
     var context = new DataServiceContext(new Uri("http://127.0.0.1/" + Guid.NewGuid().ToString()));
     bool sendingRequestCalled = false;
     context.SendingRequest2 += delegate(object o, SendingRequest2EventArgs args)
     {
         sendingRequestCalled = true;
         uri = args.RequestMessage.Url;
     };
     try
     {
         AssetData asset = new AssetData() {Id = Guid.NewGuid().ToString()};
         context.AttachTo("Assets", asset);
         context.DeleteObject(asset);
         adapter.Adapt(context);
         context.SaveChanges();
     }
     catch (DataServiceRequestException ex)
     {
         Debug.WriteLine(ex.Message);
     }
     Assert.IsTrue(sendingRequestCalled);
     return uri;
 }
开发者ID:JeromeZhao,项目名称:azure-sdk-for-media-services,代码行数:25,代码来源:AssetDeleteOptionsRequestAdapterTests.cs

示例2: EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer

        public void EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer()
        {
            // Fix URI composition in Astoria for V3 payloads
            ctx = new DataServiceContext(web.ServiceRoot, Microsoft.OData.Client.ODataProtocolVersion.V4);
            ctx.EnableAtom = true;
            ctx.Format.UseAtom();
            // Create new office type
            EFFKClient.Office o = new EFFKClient.Office() { ID = 1, BuildingName = "Building 35", FloorNumber = 2, OfficeNumber = 2173 };
            ctx.AddObject("CustomObjectContext.Offices", o);

            // create new employee type
            EFFKClient.Worker e = new EFFKClient.Worker() { ID = 1, FirstName = "Pratik", LastName = "Patel" };
            ctx.AddObject("CustomObjectContext.Workers", e);

            // Establish relationship between employee and office
            ctx.SetLink(o, "Worker", e);
            ctx.SetLink(e, "Office", o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);

            // clean the context
            ctx.DeleteObject(e);
            ctx.DeleteObject(o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:24,代码来源:Dev10EF4FKTests.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: UpdateNamedStreamOnDeletedEntity

        public void UpdateNamedStreamOnDeletedEntity()
        {
            // Calling SetSaveStream on deleted entity is not supported
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType));

            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();

                context.DeleteObject(c);

                try
                {
                    context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true /*closeStream*/, "image/jpeg");
                }
                catch (DataServiceClientException ex)
                {
                    Assert.AreEqual(ex.Message, DataServicesClientResourceUtil.GetString("Context_SetSaveStreamOnInvalidEntityState", EntityStates.Deleted), "Error Message not as expected");
                }
            }
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:29,代码来源:NamedStreamTests.cs

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

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

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


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