本文整理汇总了C#中DataServiceContext.AttachTo方法的典型用法代码示例。如果您正苦于以下问题:C# DataServiceContext.AttachTo方法的具体用法?C# DataServiceContext.AttachTo怎么用?C# DataServiceContext.AttachTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataServiceContext
的用法示例。
在下文中一共展示了DataServiceContext.AttachTo方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetupSerializerAndCallWriteEntry
/// <summary>
/// Instantiates a new Serializer class and calls WriteEntry method on it.
/// </summary>
/// <param name="dataServiceContext"></param>
/// <returns></returns>
private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext)
{
Person person = new Person();
Address address = new Address();
Car car1 = new Car();
person.Cars.Add(car1);
person.HomeAddress = address;
dataServiceContext.AttachTo("Cars", car1);
dataServiceContext.AttachTo("Addresses", address);
var requestInfo = new RequestInfo(dataServiceContext);
var serializer = new Serializer(requestInfo);
var headers = new HeaderCollection();
var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
var entityDescriptor = new EntityDescriptor(clientModel);
entityDescriptor.State = EntityStates.Added;
entityDescriptor.Entity = person;
var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) };
var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);
serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
return person;
}
示例2: 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
示例3: ClientSerializeGeographyTest_Update
public void ClientSerializeGeographyTest_Update()
{
DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
ctx.AttachTo("Entities", testEntity);
ctx.UpdateObject(testEntity);
ClientSerializeGeographyTest_Validate(ctx);
}
示例4: ProcessForeignKeys
private void ProcessForeignKeys(DataServiceContext dataServiceContext, object dataObject, IDictionary values)
{
foreach (string key in values.Keys) {
// Check if it looks like a FK, e.g. Category.CategoryID
string[] parts = key.Split('.');
if (parts.Length != 2)
continue;
// Get the name of the entity ref property, e.g. Category
string entityRefPropertyName = parts[0];
// Get the PropertyInfo for the entity ref property
PropertyInfo propInfo = dataObject.GetType().GetProperty(entityRefPropertyName);
object entityRefObject = null;
if (values[key] != null) {
// Create an 'empty' related entity, e.g a Category
entityRefObject = Activator.CreateInstance(propInfo.PropertyType);
// Set the PK in the related entity, e.g. set the CategoryID in the Category
PropertyInfo subPropInfo = propInfo.PropertyType.GetProperty(parts[1]);
subPropInfo.SetValue(
entityRefObject,
Convert.ChangeType(values[key], subPropInfo.PropertyType),
null);
}
// Find the entity set property for the association table e.g. Categories
PropertyInfo entitySetProp = DataServiceUtilities.FindEntitySetProperty(
dataServiceContext.GetType(), propInfo.PropertyType);
// Attach the related entity and set it as the link on the main entity
if (entitySetProp != null) {
if (entityRefObject != null) {
dataServiceContext.AttachTo(entitySetProp.Name, entityRefObject);
}
dataServiceContext.SetLink(dataObject, entityRefPropertyName, entityRefObject);
}
}
}
示例5: InnerSubmit
private void InnerSubmit(DataServiceContext dataContext)
{
if (!string.IsNullOrWhiteSpace(this.TemplateId))
{
dataContext.AddObject(JobBaseCollection.JobSet, this);
foreach (IAsset asset in this.InputMediaAssets)
{
AssetData target = asset as AssetData;
if (target == null)
{
throw new ArgumentException(StringTable.ErrorInputTypeNotSupported);
}
dataContext.AttachTo(AssetCollection.AssetSet, asset);
dataContext.AddLink(this, InputMediaAssetsPropertyName, target);
}
}
else
{
X509Certificate2 certToUse = null;
Verify(this);
dataContext.AddObject(JobBaseCollection.JobSet, this);
List<AssetData> inputAssets = new List<AssetData>();
AssetNamingSchemeResolver<AssetData, OutputAsset> assetNamingSchemeResolver = new AssetNamingSchemeResolver<AssetData, OutputAsset>(inputAssets);
foreach (ITask task in ((IJob)this).Tasks)
{
Verify(task);
TaskData taskData = (TaskData)task;
if (task.Options.HasFlag(TaskOptions.ProtectedConfiguration))
{
ProtectTaskConfiguration(taskData, ref certToUse, dataContext);
}
taskData.TaskBody = CreateTaskBody(assetNamingSchemeResolver, task.InputAssets.ToArray(), task.OutputAssets.ToArray());
taskData.InputMediaAssets.AddRange(task.InputAssets.OfType<AssetData>().ToArray());
taskData.OutputMediaAssets.AddRange(
task.OutputAssets
.OfType<OutputAsset>()
.Select(
c =>
{
AssetData assetData = new AssetData { Name = c.Name, Options = (int)c.Options, AlternateId = c.AlternateId };
assetData.InitCloudMediaContext(this._cloudMediaContext);
return assetData;
})
.ToArray());
dataContext.AddRelatedObject(this, TasksPropertyName, taskData);
}
foreach (IAsset asset in inputAssets)
{
dataContext.AttachTo(AssetCollection.AssetSet, asset);
dataContext.AddLink(this, InputMediaAssetsPropertyName, asset);
}
}
}
示例6: AttachAndLog
private static void AttachAndLog(StringBuilder output, DataServiceContext ctx, string entitySetName, object entity)
{
try
{
ctx.AttachTo(entitySetName, entity);
EntityDescriptor entityDescriptor = ctx.Entities[0];
entityDescriptor.Identity.Should().Be(entityDescriptor.EditLink.AbsoluteUri);
output.AppendLine(entityDescriptor.EditLink.OriginalString);
ctx.Detach(entity);
}
catch (Exception e)
{
var exception = e;
while (exception != null)
{
output.Append(exception.GetType().FullName);
output.Append(": ");
output.AppendLine(exception.Message);
exception = exception.InnerException;
}
}
}
示例7: AttachShouldFailOnNullKeys
public void AttachShouldFailOnNullKeys()
{
var ctx = new DataServiceContext(new Uri("http://test.org/test"));
Action withNullKey = () => ctx.AttachTo("EntitySet1", new SingleKeyType { Property = null });
withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property"));
withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = null, Property2 = "bar" });
withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property1"));
withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = "foo", Property2 = null });
withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property2"));
}
示例8: 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;
}
}
示例9: ContextShouldCreateStructuredValueOnAttach
public void ContextShouldCreateStructuredValueOnAttach()
{
var ctx = new DataServiceContext(new Uri("http://test.org/"), ODataProtocolVersion.V4);
ctx.AttachTo("Customers", new Customer());
ctx.Entities[0].EdmValue.Should().BeAssignableTo<ClientEdmStructuredValue>();
}
示例10: SerializeEnity_NullableEnumProperty
public void SerializeEnity_NullableEnumProperty()
{
MyEntity1 myEntity1 = new MyEntity1()
{
ID = 2,
MyColorValue = null,
MyFlagsColorValue = MyFlagsColor.Blue,
ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red },
MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red },
MyColorCollection = new List<MyColor?> { MyColor.Green, null }
};
DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
dataServiceContext.EnableAtom = true;
dataServiceContext.Format.UseAtom();
dataServiceContext.AttachTo("MyEntitySet1", myEntity1);
var requestInfo = new RequestInfo(dataServiceContext);
var serializer = new Serializer(requestInfo);
var headers = new HeaderCollection();
var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
var entityDescriptor = new EntityDescriptor(clientModel);
entityDescriptor.State = EntityStates.Added;
entityDescriptor.Entity = myEntity1;
var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
var linkDescriptors = new LinkDescriptor[] { };
var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);
serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
// read result:
MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
stream.Position = 0;
string payload = (new StreamReader(stream)).ReadToEnd();
payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
payload.Should().Be(
"{\"ComplexValue1Value\":{\"MyColorValue\":\"Green\",\"MyFlagsColorValue\":\"Red\",\"StringValue\":null},\"ID\":2,\"MyColorCollection\":[\"Green\",null],\"MyColorValue\":null,\"MyFlagsColorCollection1\":[\"Blue\",\"Red\",\"Red\"],\"MyFlagsColorValue\":\"Blue\"}");
}
示例11: SerializeEnity_EnumProperty
public void SerializeEnity_EnumProperty()
{
MyEntity1 myEntity1 = new MyEntity1()
{
ID = 2,
MyColorValue = MyColor.Yellow,
MyFlagsColorValue = MyFlagsColor.Blue,
ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red },
MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red },
MyColorCollection = new List<MyColor?>()
};
DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
dataServiceContext.EnableAtom = true;
dataServiceContext.Format.UseAtom();
dataServiceContext.AttachTo("MyEntitySet1", myEntity1);
var requestInfo = new RequestInfo(dataServiceContext);
var serializer = new Serializer(requestInfo);
var headers = new HeaderCollection();
headers.SetHeader("Content-Type", "application/atom+xml;odata.metadata=minimal");
var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
var entityDescriptor = new EntityDescriptor(clientModel);
entityDescriptor.State = EntityStates.Added;
entityDescriptor.Entity = myEntity1;
var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
var linkDescriptors = new LinkDescriptor[] { };
var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);
serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
// read result:
MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
stream.Position = 0;
string payload = (new StreamReader(stream)).ReadToEnd();
payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
payload.Should().Be(
"<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" " +
"xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" " +
"xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\">" +
"<id />" +
"<title />" +
//"<updated>2013-11-11T19:29:54Z</updated>" +
"<author><name /></author>" +
"<content type=\"application/xml\">" +
"<m:properties>" +
"<d:ComplexValue1Value>" +
"<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Green</d:MyColorValue>" +
"<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Red</d:MyFlagsColorValue>" +
"<d:StringValue m:null=\"true\" />" +
"</d:ComplexValue1Value>" +
"<d:ID m:type=\"Int64\">2</d:ID>" +
"<d:MyColorCollection />" +
"<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Yellow</d:MyColorValue>" +
"<d:MyFlagsColorCollection1>" +
"<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Blue</m:element>" +
"<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" +
"<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" +
"</d:MyFlagsColorCollection1>" +
"<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Blue</d:MyFlagsColorValue>" +
"</m:properties>" +
"</content>" +
"</entry>");
}
示例12: SerializeEnity_TwoNavigationLinksInJsonFormat
public void SerializeEnity_TwoNavigationLinksInJsonFormat()
{
var person = new Person
{
ID = 100,
Name = "Bing",
};
var car1 = new Car { ID = 1001 };
var car2 = new Car { ID = 1002 };
DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
dataServiceContext.AttachTo("Persons", person);
dataServiceContext.AttachTo("Cars", car1);
dataServiceContext.AttachTo("Cars", car2);
dataServiceContext.AddLink(person, "Cars", car1);
dataServiceContext.AddLink(person, "Cars", car2);
var requestInfo = new RequestInfo(dataServiceContext);
var serializer = new Serializer(requestInfo);
var headers = new HeaderCollection();
var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
var entityDescriptor = new EntityDescriptor(clientModel);
entityDescriptor.State = EntityStates.Added;
entityDescriptor.Entity = person;
entityDescriptor.EditLink = new Uri("http://www.foo.com/custom");
var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "Cars", car2, clientModel)};
var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);
serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
// read result:
MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
stream.Position = 0;
string payload = (new StreamReader(stream)).ReadToEnd();
payload.Should().Be(
"{\"ID\":100,\"Name\":\"Bing\",\"[email protected]\":[\"http://www.odata.org/service.svc/Cars(1001)\",\"http://www.odata.org/service.svc/Cars(1002)\"]}");
}