I want to insert 2 new records in their tables and also to create the relation many to many.
There are a lot of questions with this topic, I tried many of the answers and now I have no idea why my code is not working.
Please help me!
This is the code:
class Program
{
static void Main(string[] args)
{
MyContext db = new MyContext();
var st1 = new Student() { Name = "Joe" };
var c1 = new Course() { Name = "Math" };
db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
db.SaveChanges();
}
}
public class Student
{
public Student()
{
Courses = new HashSet<Course>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany(p => p.Courses)
.WithMany(d => d.Students)
.Map(t =>
{
t.MapLeftKey("studentId");
t.MapRightKey("courseid");
t.ToTable("StudentCourse");
});
base.OnModelCreating(modelBuilder);
}
}
Edit: Like sugested, I initialized the Courses:
public Student()
{
Courses = new HashSet<Course>();
}
and now I get this error on db.SaveChanges();
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.