使用Relation插入Azure移动应用程序TableController

时间:2017-01-04 20:47:49

标签: azure xamarin xamarin.forms azure-mobile-services

我想将Xamarin.Forms移动应用程序中的Parent和Child对象插入Azure Mobile Apps服务器。我可以通过TableController Post方法获得Parent和/或Child对象,但我永远不能让Child与Parent相关。

以下代码剪辑的结果是插入了Parent,但Child插入失败,因为在Parent上违反了唯一键约束(我相信它试图插入另一个Parent而不是链接)。

如果我只是尝试插入Child而不插入Parent,那么它确实插入了Parent但是有000 ... 000 Parent.Id

这似乎是一项非常常见的任务,但我找不到有用的教程或答案。我能找到的每个体面的Azure移动应用程序教程都是使用单表ToDo示例,该示例有效,但缺少关系示例。

我的服务器端型号是:

public class Parent : EntityData
{
    public string Description { get; set; }
    //public ICollection<Child> Childs { get; set; }
}

public class Child : EntityData
{
    public string Description { get; set; }
    public Parent Parent { get; set; }
}

和我的服务器TableController Post看起来像(对于Parent):

public class ParentController : TableController<Parent>
{
    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        MyContext context = new MyContext();
        DomainManager = new EntityDomainManager<Parent>(context, Request);
    }
    // POST tables/Parent
    public async Task<IHttpActionResult> PostParent(Parent item)
    {
        Parent current = await InsertAsync(item);
        return CreatedAtRoute("Tables", new { id = current.Id }, current);
    }
}

和(对于孩子):

public class ChildController : TableController<Child>
{
    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        MyContext context = new MyContext();
        DomainManager = new EntityDomainManager<Child>(context, Request);
    }

    // POST tables/Child
    public async Task<IHttpActionResult> PostChild(Child item)
    {
        Child current = await InsertAsync(item);
        return CreatedAtRoute("Tables", new { id = current.Id }, current);
    }

}

在Xamarin.Forms移动端,我有模型:

public class Parent
{
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }
    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }
}

public class Child 
{
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }
    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }
    public Parent Parent { get; set; }
}

和Xamarin.Forms插入命令是:

private async Task PostParentTask()
{
    Parent Parent = new Parent { Description = "New Parent" };
    await App.MobileService.GetTable<Parent>().InsertAsync(Parent);
    await Application.Current.MainPage.DisplayAlert("Parent", string.Format("{0} was posted with GUID {1}", Parent.Description, Parent.Id), "OK");
    Child Child = new Child { Description = "New Child", Parent = Parent};
    await App.MobileService.GetTable<Child>().InsertAsync(Child);
}

1 个答案:

答案 0 :(得分:1)

您无法与Azure移动应用程序建立直接关系。

您必须解除关系,然后分别推送每个表。

阅读http://aka.ms/zumobook - 特别是第3章,其中涉及关系主题。