本文整理汇总了C#中DataServiceContext.SaveChanges方法的典型用法代码示例。如果您正苦于以下问题:C# DataServiceContext.SaveChanges方法的具体用法?C# DataServiceContext.SaveChanges怎么用?C# DataServiceContext.SaveChanges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataServiceContext
的用法示例。
在下文中一共展示了DataServiceContext.SaveChanges方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例3: EdmValidNamesNotAllowedInUri
public void EdmValidNamesNotAllowedInUri()
{
DSPMetadata metadata = new DSPMetadata("Test", "TestNS");
var entityType = metadata.AddEntityType("MyType", null, null, false);
metadata.AddKeyProperty(entityType, "ID", typeof(int));
metadata.AddPrimitiveProperty(entityType, "Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", typeof(string));
var resourceSet = metadata.AddResourceSet("EntitySet", entityType);
metadata.SetReadOnly();
DSPServiceDefinition service = new DSPServiceDefinition()
{
Metadata = metadata,
Writable = true
};
DSPContext data = new DSPContext();
service.CreateDataSource = (m) => { return data; };
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
DataServiceContext context = new DataServiceContext(request.ServiceRoot);
context.EnableAtom = true;
context.Format.UseAtom();
string value = "value of Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ";
context.AddObject("EntitySet", new MyType() {
ID = 1,
Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ = value,
});
context.SaveChanges();
var result = context.Execute<MyType>(new Uri("EntitySet?$orderby=Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", UriKind.Relative)).First();
Assert.AreEqual(value, result.Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ, "The roundtrip value not as expected");
}
}
示例4: CreateStorageContentKey
private static ContentKeyData CreateStorageContentKey(AssetData tempAsset, NullableFileEncryption fileEncryption, DataServiceContext dataContext)
{
// Create the content key.
fileEncryption.Init();
// Encrypt it for delivery to Nimbus.
X509Certificate2 certToUse = ContentKeyCollection.GetCertificateToEncryptContentKey(dataContext, ContentKeyType.StorageEncryption);
ContentKeyData contentKeyData = ContentKeyBaseCollection.CreateStorageContentKey(fileEncryption.FileEncryption, certToUse);
dataContext.AddObject(ContentKeyCollection.ContentKeySet, contentKeyData);
dataContext.SaveChanges();
// Associate it with the asset.
((IAsset) tempAsset).ContentKeys.Add(contentKeyData);
return contentKeyData;
}
示例5: 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
示例6: Collection_IExpandProvider
public void Collection_IExpandProvider()
{
var metadata = CreateMetadataForXFeatureEntity();
DSPServiceDefinition service = new DSPServiceDefinition()
{
Metadata = metadata,
CreateDataSource = (m) => new DSPContext(),
Writable = true,
SupportIExpandProvider = true
};
string[] responseFormats = new string[] { UnitTestsUtil.AtomFormat };
TestUtil.RunCombinations(responseFormats, (format) =>
{
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
PopulateClientContextWithTestEntities(ctx);
// set navigation
((XFeatureTestsEntity)ctx.Entities.Last().Entity).NextTestEntity = (XFeatureTestsEntity)ctx.Entities.First().Entity;
ctx.SetLink(ctx.Entities.Last().Entity, "NextTestEntity", ctx.Entities.First().Entity);
ctx.SaveChanges();
request.RequestUriString = "/Entities?$expand=NextTestEntity";
request.Accept = format;
request.SendRequest();
XDocument resp = UnitTestsUtil.GetResponseAsAtomXLinq(request);
Assert.IsNotNull(resp.Descendants(UnitTestsUtil.MetadataNamespace + "inline").Elements(UnitTestsUtil.AtomNamespace + "entry").FirstOrDefault(), "No expanded entities in the payload.");
foreach (XFeatureTestsEntity entity in ctx.Entities.Select(e => e.Entity))
{
var entityXElement = (from e in resp.Element(UnitTestsUtil.AtomNamespace + "feed").Elements(UnitTestsUtil.AtomNamespace + "entry")
where (int)e.Element(UnitTestsUtil.AtomNamespace + "content")
.Element(UnitTestsUtil.MetadataNamespace + "properties")
.Element(UnitTestsUtil.DataNamespace + "ID") == entity.ID
select e).Single();
ValidateResult(entity, entityXElement);
}
}
});
}
示例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");
}
}
示例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.");
};
}
示例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;
}
});
}
示例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"));
}
});
}
示例11: PopulateClientContextWithTestEntities
private static void PopulateClientContextWithTestEntities(DataServiceContext context)
{
foreach (var entity in CreateClientTestEntities())
{
context.AddObject("Entities", entity);
}
context.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
}
示例12: 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);
}
}