I have a Subject
class and a Course
class. They are in a many-to-many relationship so I also have a CourseSubject
class with navigation properties and id properties to the other two classes. I can now read subjects and courses from the database but whenever I try to save eg. an updated Subject
instance, I get a MySqlException that it failed to save to the CourseSubject
table… even though the table name is CourseSubjects
(plural)!
public partial class Subject
{
public string Id { get; set; } = null!;
public string Title { get; set; } = null!;
public string Descrip { get; set; } = null!;
public virtual ICollection<Course> ParentCourses { get; set; }
}
public partial class Course
{
public string Id { get; set; } = null!;
public string Title { get; set; } = null!;
public string Descrip { get; set; } = null!;
public virtual ICollection<Subject> Subjects { get; set; }
}
public partial class CourseSubject
{
public string CourseId { get; set; } = null!;
public virtual Course Course { get; set; }
public string SubjectId { get; set; } = null!;
public virtual Subject Subject { get; set; }
public string? PrevSubjectInCourseId { get; set; }
public string? NextSubjectInCourseId { get; set; }
public string? ReasonToBeInCourse { get; set; }
}
My OnModelCreating():
modelBuilder.Entity<CourseSubject>(entity =>
{
entity.HasKey(e => new { e.CourseId, e.SubjectId })
.HasName("PRIMARY")
.HasAnnotation("MySql:IndexPrefixLength", new[] { 0, 0 });
});
modelBuilder.Entity<CourseSubject>().ToTable("CourseSubjects", "dbo");
modelBuilder.Entity<CourseSubject>()
.HasOne(cs => cs.Subject);
modelBuilder.Entity<CourseSubject>()
.HasOne(cs => cs.Course);
From the generated SQL query I can see it makes the Subject and the Course plural, instead of the CourseSubject:
I’ve tried using the [Table("CourseSubjects")]
attribute on the CourseSubject class. I’ve tried adding the explicit table name for the model builder
modelBuilder.Entity<CourseSubject>().ToTable("CourseSubjects", "dbo");
Nothing helps. The other tables are also plural and they work fine. What am I doing wrong?
2
Answers
Please add your Exception detail to check,
I think it’s not related to your table name unless there is a difference between your table name and your entity name, but I think they have the same name, so share more details about the problem,
try this:
and be sure your table exists in your db,
Edited:
You are using Many-to-many with class for join entity, hence it needs some additional fluent configuration to associate the join entity with the skip navigations, map its navigations, FKs, table and columns names etc. All this with some of the
UsingEntity
overloads.For instance: