如何将多个对象插入Azure移动服务表控制器[.Net后端]

Fri*_*ren 4 azure c#-4.0 azure-mobile-services

我有一个以.net Web Api编码的Azure Mobile服务.我有一个TableController.我希望该表控制器能够插入多个人,而不仅仅是一个人使用InsertAsync(myPerson)从客户端插入.我在TableController中有以下代码:

[RequiresAuthorization(AuthorizationLevel.Admin)]        
public async Task<bool> InsertPersons(List<Person> values)
  {
     try
      {
        foreach (var item in values)
         {                   
                var current = await InsertAsync(item);
         }
         return true;
      }
      catch (System.Exception)
       {
            return false;
       }
  }
Run Code Online (Sandbox Code Playgroud)

问题出在客户端.因为它是强类型的,它只允许我一次插入一个项目.我该如何从客户端调用服务器?我是否必须编写自定义Api控制器并将其调用mobileService.InvokeApiAsync?如果是这样,我如何从不从TableController继承的Custom Api Controller访问我的数据库?

非常感谢!

car*_*ira 11

TableController<T>基类中的辅助方法假定插入操作适用于单个对象 - 并且客户端中的InsertAsync方法也假设相同.因此,即使您可以在表控制器中定义一个接收Person的数组(或列表)的方法,您也无法通过客户端SDK调用它(至少在没有使用处理程序的情况下进行繁重调用时,例).

但是,您可以创建一个自定义API来获取此类列表.要从API中插入多个项,您可以直接访问上下文,而无需通过表中的辅助方法:

public class PersonController : ApiController
{
    test20140807Context context;

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        this.context = new test20140807Context();
    }

    [HttpPost]
    public async Task<bool> InsertPersons(List<Person> values)
    {
        foreach (var value in values)
        {
            if (string.IsNullOrEmpty(value.Id))
            {
                value.Id = Guid.NewGuid().ToString();
            }
        }

        try
        {
            this.context.People.AddRange(values);
            await this.context.SaveChangesAsync();

            return true;
        }
        catch (System.Exception ex)
        {
            Trace.WriteLine("Error: " + ex);
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在客户端:

private async void btnTest_Click(object sender, RoutedEventArgs e)
{
    var items = new Person[]
    {
        new Person { Name = "John Doe", Age = 33 },
        new Person { Name = "Jane Roe", Age = 32 }
    };
    try
    {
        var response = await App.MobileService.InvokeApiAsync<Person[], bool>("person", items);
        Debug.WriteLine("response: " + response);
    }
    catch (Exception ex)
    {
        var str = ex.ToString();
        Debug.WriteLine(str);
    }
}
Run Code Online (Sandbox Code Playgroud)