简体   繁体   中英

How can i save a list of object in sqlite in xamarin forms

I have two classes (Reminder and Tasks) and the Reminder class contains a list of Task class which i want to save to sqlite at the same time when i am saving the reminder so some List of task can contain identical ReminderId so they can be retrieved alongside a Reminder object. In other words, I am trying to save List of Tasks and have them attached to a reminderId so they can be retrieved as a property of Reminder Class. However, when i save this information, every other property are saved except the list of Tasks which returns null when i am trying to read from db.

I have read the sqlite-extension docs and didnt find it helpful enough. I have also tried and looked for other answers on here but they didnt come out clear enough or they are not exactly what i need.

This is my Reminder Class:

  public class Reminder
    {
        [PrimaryKey] [AutoIncrement]
        public int ReminderId { get; set; }
        public bool Status { get; set; }
        public string ReminderLocation { get; set; }
        //in terms of days
        public DateTime ReminderCreationDate { get; set; }

        [OneToMany(CascadeOperations = CascadeOperation.All)]
        public List<Tasks> ThingsTodo { get; set; }

This is my Tasks Class:

 public class Tasks
    {
        [AutoIncrement]
        [PrimaryKey]
        public int TaskId { get; set; }
        public string Events { get; set; }

        [ForeignKey(typeof(Reminder))]
        public int ReminderId { get; set; }

        [ManyToOne]
        public Reminder Reminders { get; set; }

    }

This is how i am saving the reminder object in db:

  private async void AddReminder (object sender, EventArgs e)
        {


            var ReminderData = new Reminder
            {
                ReminderCreationDate = DateTime.Now,
                Status = false,
                ReminderLocation = locationentry.Text,
               ThingsTodo = new List<Tasks>(tasks)
            };


            if(tasks.Count <= 0 || string.IsNullOrWhiteSpace(locationentry.Text))
            {
               await DisplayAlert("Hey boss!", "I need a location and at least a task to get this done", "ok");
            }
            else
            {
                await controller.AddReminder(ReminderData);

                DependencyService.Get<IToast>().ShowMessage("Reminder Created boss");
                locationentry.Text = "";
                tasks.Clear();
            }            

        }

This my controller for saving Reminder object:

 public async Task AddReminder(Reminder reminder)
        {

            await dbconnection.InsertAsync(reminder);                      
        }

I expect to be able to save a Reminder object alongside a list of Tasks and each of this tasks having same ReminderId so they can be retrieved as a part of the Reminder object. I dont know how i am supposed to save the Tasks and Reminder. Please help me inspect my code and tell me what i am doing wrong

According to your description, you want to save list onject into Sqlite database, I suggest you can use Text blobbed properties , from SQLite-Net Extensions library .

 public class Reminder
{
    [PrimaryKey]
    [AutoIncrement]
    public int ReminderId { get; set; }
    public bool Status { get; set; }
    public string ReminderLocation { get; set; }
    //in terms of days
    public DateTime ReminderCreationDate { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<Tasks> ThingsTodo { get; set; }
    [TextBlob(nameof(Taskblodded))]
    public string Taskblodded { get; set; }
}

Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows storing simple objects in the same table in a single column.

Text-blobbed properties have a small overhead of serializing and deserializing the objects and some limitations, but are the best way to store simple objects like List or Dictionary of basic types or simple relationships. Text-blobbed properties require a declared string property where the serialized object is stored.

Text-blobbed properties cannot have relationships to other objects nor inverse relationship to its parent.

A JSON-based serializer is used if no other serializer has been specified using TextBlobOperations.SetTextSerializer method. To use the JSON serializer, a reference to Newtonsoft Json.Net library must be included in the project, also available as a NuGet package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM