问题
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