【问题标题】:Android Azure delete all rowsAndroid Azure 删除所有行
【发布时间】:2016-07-05 17:34:34
【问题描述】:

我正在使用 Azure 移动服务构建一个带有 Azure 数据库(在 Xamarin 中)的 Android 应用程序。 我想从它的记录中清除一个表。
虽然有一个“table.RemoveAsync”,但我不确定如何选择所有行。
是“选择”还是“在哪里”? 我会很感激一些帮助。

这是我的代码:

    //Mobile Service Client reference
    private MobileServiceClient client;

    //Mobile Service sync table used to access data
    private IMobileServiceSyncTable<Mashlim> mashlimTable;

    const string applicationURL = @"http://blahblah.azurewebsites.net/";


    public override async void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        CurrentPlatform.Init();

        // Create the Mobile Service Client instance, using the provided
        // Mobile Service URL
        client = new MobileServiceClient(applicationURL);
        await InitLocalStoreAsync();

        // Get the Mobile Service sync table instance to use
        mashlimTable = client.GetSyncTable<Mashlim>();

    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var view = inflater.Inflate(Resource.Layout.ShabbatMinyan, container, false);
        ….

        OnRefreshItemsSelected();

        return view;
    }

    private async Task InitLocalStoreAsync()
    {
        // new code to initialize the SQLite store
        string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);

        if (!File.Exists(path))
        {
            File.Create(path).Dispose();
        }

        var store = new MobileServiceSQLiteStore(path);
        store.DefineTable<Mashlim>();

        // Uses the default conflict handler, which fails on conflict
        // To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
        await client.SyncContext.InitializeAsync(store);
    }

    private async Task SyncAsync()
    {
        try
        {
            await client.SyncContext.PushAsync();
            await mashlimTable.PullAsync("allMashlims", mashlimTable.CreateQuery()); // query ID is used for incremental sync
        }
        catch (Java.Net.MalformedURLException)
        {
            CreateAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
        }
        catch (Exception e)
        {
            CreateAndShowDialog(e, "Error");
        }
    }

    // Called when the refresh menu option is selected
    private async void OnRefreshItemsSelected()
    {
        await SyncAsync(); // get changes from the mobile service
        await RefreshItemsFromTableAsync(); // refresh view using local database
    }

    //Refresh the list with the items in the local database
    private async Task RefreshItemsFromTableAsync()
    {
        try
        {
            // Get the items that were marked as mashlim and add them to list
            var list = await mashlimTable.Where(item => item.IsMashlim == true).ToListAsync();

            mashlimim = 0;
            foreach (Mashlim current in list)
                mashlimim++;

            mashlimimNumText.Text = mashlimim.ToString();
        }
        catch (Exception e)
        {
            CreateAndShowDialog(e, "Error");
        }
    }

    [Java.Interop.Export()]
    public async void AddItem()
    {
        if (client == null)
        {
            return;
        }

        if(Settings.MashlimId==string.Empty)
        {

            // Create a new item
            item = new Mashlim
            {
                Name = nameText.Text,
                PhoneNumber = phoneText.Text,
                IsMashlim = true
            };


            try
            {
                await mashlimTable.InsertAsync(item); // insert the new item into the local database
                await SyncAsync(); // send changes to the mobile service
                await RefreshItemsFromTableAsync();
                Settings.MashlimId = item.Id;
                Settings.MashlimName = item.Name;
                Settings.IsMashlim = true;
                Settings.MashlimPhone = item.PhoneNumber;
            }
            catch (Exception e)
            {
                CreateAndShowDialog(e, "Error");
            }
        }

        else
        {
            Settings.IsMashlim = true;
            item = new Mashlim
            {
                Id = Settings.MashlimId,
                Name = Settings.MashlimName,
                IsMashlim = Settings.IsMashlim,
                PhoneNumber = Settings.MashlimPhone
            };


            try
            {
                await mashlimTable.UpdateAsync(item); // insert the new item into the local database
                await SyncAsync(); // send changes to the mobile service
                await RefreshItemsFromTableAsync();
                mashlim = true;
            }
            catch (Exception e)
            {
                CreateAndShowDialog(e, "Error");
            }
        }
    }

}
}

谢谢。

【问题讨论】:

    标签: c# android azure xamarin azure-mobile-services


    【解决方案1】:

    在客户端 SDK 中,您不能在本地 SQLite 存储上运行任意 SQL 语句。因此,您必须选择所有行并循环删除它们。 (小心使用 ToListAsync 将所有内容加载到内存中,因为这可能会耗尽设备上的内存。)请注意,如果您有 X 行,这将导致 X 服务器请求,这可能会非常慢。客户端的请求方法见这篇文章:How to: Delete data in a mobile app

    如果您想删除所有符合特定条件的行,您最好在服务器上编写自定义 API,并让客户端通过调用 API 发送一个请求。在服务器上,您可以使用 SQL 或 LINQ,具体取决于您使用的是 .NET 还是 Node.js。

    例如,使用 .NET 后端,您可以使用 How to: Define a custom API controller 创建自定义 API。

    在您的控制器方法之一中,您将拥有以下代码:

    using (var context = new YourContext())
    {
        context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE Condition = value");
    }
    

    【讨论】:

    • 谢谢。您能否就如何执行此操作(使用代码)提供一些更具体的指导,因为我对此真的很陌生并且不确定该怎么做。我使用的是 C#,而不是 Node.js。谢谢!
    • 如果我知道我的行数不会超过 100 左右,我还是不应该全部选择吗?我该怎么做呢?谢谢?
    • @amitairos 我已经用您在服务器上编写的 SQL 示例更新了我的答案。如果您的行数少于 100,则可以在客户端上使用 ToListAsync 循环遍历它们,但对于每个删除操作,您仍然会有一个服务器请求。如果你想在客户端做这个操作,那么我建议你做一些性能测试。
    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多