How to add/ load/ delete items from a foreign key table in xamarin forms with sqlite-net-pcl and sqliteExtensions

醉酒当歌 提交于 2020-07-10 10:26:30

问题


Hi i have this two tables ( not sure if they are written correctly) an agenda can contain many Tasks, my question is how do i write the methods to add/delete/load my tasks in my agenda, i am not sure how this work when you have a foreign key ? Thank you.

Agenda.cs in the Models folder

    [Table("Agenda")]
    public class Agenda
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Topic { get; set; }
        public string Duration { get; set; } 
        public DateTime Date { get; set; }
        [OneToMany(CascadeOperations = CascadeOperation.All)]
}

Tasks.cs in Models folder

[Table("Task")]
public class Tasks
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    
    [ForeignKey(typeof(Agenda))]
    public string Name { get; set; }
    public string Time { get; set; }
    [ManyToOne]
    public Agenda Agenda { get; set; }
    
}

AgendaDatabase.cs in the Database folder ( all my operation currently for the Agenda table)

public class AgendaDatabase
{
    
    readonly SQLiteAsyncConnection database;

    public AgendaDatabase(string dbPath)
    {
       
        database = new SQLiteAsyncConnection(dbPath);
        database.CreateTableAsync<Agenda>().Wait();
    


    }

    // Get all agenda
    public Task<List<Agenda>> GetAgendasAsync()
    {

        return database.Table<Agenda>().ToListAsync();
    }

    // Get specific agenda
    public Task<Agenda> GetAgendaAsync(int id)
    {
        return database.Table<Agenda>()
                        .Where(i => i.ID == id)
                        .FirstOrDefaultAsync();
    }

    // Insert new agenda (save)
    public Task<int> SaveAgendaAsync(Agenda agenda)
    {
        if (agenda.ID != 0)
        {
            return database.UpdateAsync(agenda);
        }
        else
        {
            return database.InsertAsync(agenda);
        }
    }
    
    //Delete specific agenda
    public Task<int> DeleteAgendaAsync(Agenda agenda)
    {
        return database.DeleteAsync(agenda);
    }
    public Task<int> AddAgendaAsync(Agenda agenda)
    {
        return database.InsertAsync(agenda);
    }
}

来源:https://stackoverflow.com/questions/62600651/how-to-add-load-delete-items-from-a-foreign-key-table-in-xamarin-forms-with-sq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!