Mapping many to many relationship in entity framework code first

c# ef-code-first entity-framework many-to-many

Question

I'm trying to construct a test in EF by creating a many to many relationship because I always map one to one or one to many. I got an example from the internet to attempt, but I can't read registers even if the sample works for inserting them.

Here are my classes; I have no idea what they areHashSet I notice this code on the website.

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public ICollection<Course> CoursesAttending { get; set; }

    public Person()
    {
        CoursesAttending = new HashSet<Course>();
    }
}

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }

    public ICollection<Person> Students { get; set; }

    public Course()
    {
        Students = new HashSet<Person>();
    }
}

the situation I'm in

public class SchoolContext : DbContext
{
    public DbSet<Course> Courses { get; set; }
    public DbSet<Person> People { get; set; }

    public SchoolContext()
        : base("MyDb")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Course>().
            HasMany(c => c.Students).
            WithMany(p => p.CoursesAttending).
            Map(
                m =>
                {
                    m.MapLeftKey("CourseId");
                    m.MapRightKey("PersonId");
                    m.ToTable("PersonCourses");
                });

    }
}

Is it correct when I insert registers?

static void Main(string[] args)
{
    using (SchoolContext db = new SchoolContext())
    {
        Course math = new Course();
        Course history = new Course();
        Course biology = new Course();
        math.Title = "Math";
        history.Title = "History";
        biology.Title = "Biology";

        db.Courses.Add(math);
        db.Courses.Add(history);
        db.Courses.Add(biology);

        Person john = new Person();
        john.FirstName = "John";
        john.LastName = "Paul";
        john.CoursesAttending.Add(history);
        john.CoursesAttending.Add(biology);

        db.People.Add(john);
        db.SaveChanges();
    }
}

However, it doesn't function when I try to select Register for Show Content; it just prints nothing.

static void Main(string[] args)
{
    using (SchoolContext db = new SchoolContext())
    {
        Pearson p = db.Peasons.First();
        Console.WriteLine(p.CoursesAttending.First().Title);
    }
}

I checked the database, and the registers are there. What's the issue?

Please start by showing me how to use code to create a select in a many-to-many connection.

1
19
1/16/2015 8:42:47 PM

Accepted Answer

To start, you might want to create the collections virtual to enable lazy loading.

public virtual ICollection<Course> CoursesAttending { get; set; }
public virtual ICollection<Person> Students { get; set; }

Consequently, EF is able to produce derived classes (proxies) fromCourse and Person that add logic to collections to alter the collections' data loading from the data store.

You'll observe that when you do that.

Console.WriteLine(p.CoursesAttending.First().Title);

will run an independent query to populateCoursesAttending .

As an alternative, or in addition, you may choose to do the following to avoid making repeated journeys to the database:

Person p = db.Persons.Include(p => p.CoursesAttending).First();

that brings thePerson zzz-54 theCoursesAttending with one motion.

34
3/12/2014 10:44:51 PM


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