Answer the question
In order to leave comments, you need to log in
Why doesn't an entity refer to another entity that created it?
I have a Teacher entity that creates a course. The problem is that the course, for some reason, does not reference the teacher who created it. The teacher does not refer to the course either. I tried using the Update method, but it did not help.
public async Task<CourseResponse> AddCourse(CourseAddRequest courseAddRequest, Guid teacherId)
{
var teacher = await _teacherRepository.GetTeacher(teacherId);
if (teacher == null)
{
throw new Exception("User doesn't exist");
}
var course = _mapper.Map<Course>(courseAddRequest);
course.Teacher = teacher;
course.TeacherId = teacher.Id;
var addedCourse = await _courseRepository.AddCourse(course);
teacher.Courses.Add(addedCourse);
teacher = await _teacherRepository.UpdateTeacher(teacher);
return _mapper.Map<CourseResponse>(addedCourse);
}
public class Teacher : BaseEntity
{
public string Name { get; set; }
public string LastName { get; set; }
public List<Course> Courses { get; set; } = new List<Course>();
}
public class Course : BaseEntity
{
public string Header { get; set; }
public string Description { get; set; }
public Guid TeacherId { get; set; }
public Teacher Teacher { get; set; }
public List<Student> StudentsOnCourse { get; set; } = new List<Student>();
}
class CourseEntityTypeConfiguration : IEntityTypeConfiguration<Course>
{
public void Configure(EntityTypeBuilder<Course> builder)
{
builder.HasOne(c => c.Teacher)
.WithMany(t => t.Courses)
.HasForeignKey(c => c.TeacherId);
}
}
public class UniDbContext : DbContext
{
public UniDbContext(DbContextOptions<UniDbContext> options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(CourseEntityTypeConfiguration).Assembly);
}
}
services.AddDbContext<UniDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
sqlOpt => sqlOpt.MigrationsAssembly(typeof(UniDbContext).Assembly.FullName)
));
Answer the question
In order to leave comments, you need to log in
Yes, you just need to write Include so that related entities are loaded. This will turn into a join on the sql side. By default, loading related entities is disabled.
public async Task<Teacher> GetTeacher(Guid teacherId)
{
var teacher = await _uniDbContext
.Teachers
.Include(x => x.Cources)
.FirstOrDefaultAsync(t => t.Id == teacherId);
return teacher;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question