I am trying to build a simple example where I have Projects, each project will have own time schedule, time schedule will consist of tasks. Currently I have built my interface so that user is able to add new Project to ComboBox. Then by selecting project I would like to retrieve table of Tasks related to that project. It looks like I am missing something in building proper relation between tables and accessing them. However I am not able to figure out how to do it in a proper way?
Here is TaskModel:
using System;
using System.ComponentModel.DataAnnotations;
namespace EFCoreApplication.Models
{
public class TaskModel
{
[Key]
public int Id { get; set; }
public string ProjectNumber { get; set; }
public string Text { get; set; }
public DateTime StartDate { get; set; }
public int Duration { get; set; }
public decimal Progress { get; set; }
public int? ParentId { get; set; }
public string Type { get; set; }
public int ProjectId { get; set; }
public virtual ProjectModel ProjectModel { get; set; }
}
}
Here is ProjectModel:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EFCoreApplication.Models
{
public class ProjectModel
{
[Key]
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public string ProjectNumber { get; set; }
public virtual ICollection<TaskModel> Tasks { get; set; }
}
}
Here is DBContext:
using EFCoreApplication.Models;
using Microsoft.EntityFrameworkCore;
namespace EFCoreApplication.Data
{
public class SQLiteDBContext : DbContext
{
public virtual DbSet<ProjectModel> ProjectModel { get; set; }
//public virtual DbSet<ProjectScheduleModel> ProjectScheduleModel { get; set; }
public virtual DbSet<TaskModel> TaskModel { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite(@"Data Source=sqlitedemo.db");
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// configures one-to-many relationship
builder.Entity<TaskModel>()
.HasOne<ProjectModel>(s => s.ProjectModel)
.WithMany(g => g.Tasks)
.HasForeignKey(k => k.ProjectId);
}
}
}
How to build proper relation in this case and how to write/read data?