Add data to new table in One-to-Many relationship using Entity Framework Core

mrw 201 Reputation points
2021-06-04T12:55:46.58+00:00

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?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,681 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,308 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
768 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,196 Reputation points
    2021-06-04T19:16:02.09+00:00

    I would recommend using Include and ThenInclude. The following example show help and note I don't include all navigations.

    Example

    public static async Task<List<Person>> PeopleTask(int identifier)  
    {  
        return await Task.Run(async () =>  
        {  
            await using var context = new SchoolContext();  
      
            var results = await context  
                .People  
                .Include(person => person.StudentGrades)  
                .ThenInclude(person => person.Course)  
                .Where(person => person.PersonID == identifier)  
                .ToListAsync();  
      
            return results;  
      
        });  
      
    }  
    

    Usage

    static async Task Main(string[] args)  
    {  
        var results = await Operations.PeopleTask(2);  
      
    }  
    

    102499-figure1.png

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-06-04T17:59:30.13+00:00

    The link should help you. You can always find articles on various topics, becuase Bing and Google search engines are your friends.

    https://softdevpractice.com/blog/many-to-many-ef-core/

    1 person found this answer helpful.
    0 comments No comments