我如何将列表保存到Xamarin形式的sqlite数据库中

时间:2019-04-06 19:59:25

标签: c# sqlite xamarin.forms

我从休息服务处收到一个列表,我想将其保存到应用程序中的sqlite数据库中。 这是我的代码:

    async void ClickOnStartAsync(object sender, EventArgs e)
    {
        lstAnswerService = await App.userManager.GetAnswerItemAsync("1");
        Answer ans_item = new Answer();
        try
        {
        foreach (var item in lstAnswerService)
        {
            ans_item.ans_Id = item.ans_Id;
            ans_item.qu_Id = item.qu_Id;
            ans_item.ans_Title = item.ans_Title;
            ans_item.isAnswer = item.isAnswer;
            ans_item.sortId = item.sortId;

            //Code for saving ans_item into sqlite database in app
        }

        }
        catch(Exception ex)
        {
            await DisplayAlert("", ex.Message.ToString(), "ok");
        }
    }

我想将列表lstAnswerService保存到sqlite

我的类和表Answerer如下:

public class Answer
{
    [PrimaryKey,AutoIncrement]
    public int ans_Id { get; set; }
    public int qu_Id { get; set; }
    public string ans_Title { get; set; }
    public bool isAnswer { get; set; }
    public int sortId { get; set; }
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

You need to create new object of Answer list Like and after that` List<Answer>  objLstAnswer = new List<Answer>` and in foreach loop you need to add ans_item object into list Like `objLstAnswer.Add(ans_item)`

Full Code below`                                               
  List<Answer>  objLstAnswer = new List<Answer>
  lstAnswerService = await App.userManager.GetAnswerItemAsync("1");
        Answer ans_item = new Answer();
        try
        {
        foreach (var item in lstAnswerService)
        {
            ans_item.ans_Id = item.ans_Id;
            ans_item.qu_Id = item.qu_Id;
            ans_item.ans_Title = item.ans_Title;
            ans_item.isAnswer = item.isAnswer;
            ans_item.sortId = item.sortId;
            objLstAnswer.Add(ans_item);
        }
        }
        catch(Exception ex)
        {
            await DisplayAlert("", ex.Message.ToString(), "ok");
        }`