Foreign key not populating in Entity Framework

.net-core asp.net-core c# entity-framework-core

Question

A table that should be connecting two of my things is not updating properly. To elaborate more... I have two entities with the relationship: Class and Teacher.

  1. A teacher may be given many courses.
  2. There may only be one instructor per class.

These two things are listed below.

public class Teacher
{
    [Required, Key]
    public Guid Id { get; private set; }
    [StringLength(50)]
    public string Name { get; set; }
    public string Email { get; set; }
    public List<Class> Classes = new List<Class>();

    public Teacher()
    {
        Id = new Guid();
    }

    public Teacher(Guid id)
    {
        Id = id;
    }

    public void AssignClass(Class newClass)
    {
        Classes.Add(newClass);
    }
}

public class Class
{
    [Required, Key]
    public Guid Id { get; private set; }
    [Required, StringLength(20)]
    public string Name { get; set; }
    [Required, Range(5, 30)]
    public int Capacity { get; set; }
    public Teacher Teacher { get; set; }
    public IEnumerable<StudentClass> StudentClasses { get; set; }

    public Class()
    {
        Id = new Guid();
    }

    public Class(Guid id)
    {
        Id = id;
    }
}

I got the anticipated foreign key of TeacherId in the Classes table when I create my migrations. As for the SQL:

CREATE TABLE [dbo].[Classes] (
[Id]        UNIQUEIDENTIFIER NOT NULL,
[Name]      NVARCHAR (20)    NOT NULL,
[Capacity]  INT              NOT NULL,
[TeacherId] UNIQUEIDENTIFIER NULL,
CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Classes_Teachers_TeacherId] FOREIGN KEY ([TeacherId]) REFERENCES [dbo].[Teachers] ([Id])
);
GO
CREATE NONCLUSTERED INDEX [IX_Classes_TeacherId]
ON [dbo].[Classes]([TeacherId] ASC);

My class's DBContext derivation appears as follows:

public class SchoolDatabaseContext : DbContext
{
    public DbSet<Student> Students { get; private set; }
    public DbSet<Class> Classes { get; private set; }
    public DbSet<Teacher> Teachers { get; private set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }

    public SchoolDatabaseContext(DbContextOptions<SchoolDatabaseContext> options) : base(options)
    {
    }
}

Not yet configured are those entities. I serve the DbContext to the controller via DI, and everything seems to be in order.

Although I tried to achieve a DDD-type structure, in order to make this problem simpler to troubleshoot, I stripped everything down to the controller, leaving me with a structure that is essentially... controls a DbContext..

Here is my controller's code:

[HttpPost]
    [Route("assign-teacher-to-class")]
    public async Task<IActionResult> AssignClass([FromBody] AssignTeacherToClass assignTeacherToClass)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var teacher = await schoolDatabaseContext.Teachers.FindAsync(assignTeacherToClass.TeacherId);

        var classToAssign = await schoolDatabaseContext.Classes.FindAsync(assignTeacherToClass.ClassId);


        teacher.AssignClass(classToAssign);

        schoolDatabaseContext.Entry(teacher).State = EntityState.Modified;

        await schoolDatabaseContext.SaveChangesAsync();

        return Ok(teacher);
}

The ids from the post body are valid when I debug through them; they are appropriately assigned to the DTO AssignClass, and the calls to the DbContext to get the data for each kind (teacher and class) are valid. I then use a method from my teacher type to add the class to the Class List property (for reference, see the teachers entity code at the beginning). I then use the DbContext method to save the changes, and The Issue Here Is: at no point does the TeacherId in the database update while I'm debugging or finishing. I've done everything that comes to mind, such as creating collections in various ways, switching collection types, searching for configuration that would make it easier to map these entities this way, removing any unnecessary layers, altering the accessibility of attributes and classes, and more.

Any assistance would be really appreciated since I feel like this relationship should be very straightforward but I am starting to feel discouraged about it. I actually used a bridge lesson to get my many to many functioning, so I was shocked to get stopped on this one:(

Thanks

1
1
8/30/2019 12:07:59 AM

Popular Answer

ZZZ_tmp
0
9/4/2019 11:47:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow