Code First MVC 4 EF 5 many-to-many Join

一曲冷凌霜 提交于 2019-12-12 05:45:38

问题


I've been struggling with this for the past few days and can't seem to figure this out. I'm using Code First approach with the MVC 4 and EF 5. I have a many-to-many relationship setup through the fluent API. Here is the sample code:

    public class Class
    {
        public Class()
        {
            Teachers = new List<User>();
        }
        /// <summary>
        /// Unique ID in the system
        /// </summary>
        [Key]
        public long Id { get; set; }

        /// <summary>
        /// Array of users (Teachers and Interventionists) associated with that class
        /// </summary>
        public List<User> Teachers { get; set; }
    }

User class:

public class User
{
    public User()
    {

    }
    /// <summary>
    ///     Unique Id in the system 
    ///</summary> 
    [Key]
    public long Id { get; set; }

    public List<Class> Classes { get; set; }
}

The fluent API is here:

    modelBuilder.Entity<Class>().HasMany(m => m.Teachers).WithMany(t => t.Classes).Map(m =>
            {
                m.ToTable("ClassTeachers");
                m.MapLeftKey("ClassId");
                m.MapRightKey("UserId");
            });

What's going on:

The EF is creating the ClassTeachers table and when I select all the classes I receive the data as expected. The Classes have the correct Teachers within the returned data.

What I need help with:

I'm trying to return all the Classes that have a specific teacher. I was trying something like this:

    var classesTeachers =
        from classes in data.Classes from u in data.Users
        where u.Id == mockUser.Id
        select new { classes.Id, classes.Label, u.FirstName };

However, I'm not getting back the correct data. Normally, there would be a third table that I could join in between to get back the required results, however, this isn't available with the EF Code First approach. I'm really at a loss...

Thank you.


回答1:


Try this:

var classesTeachers = from c in data.Classes
                      where c.Teachers.Any(t => t.Id == mockUser.Id)
                      select c;


来源:https://stackoverflow.com/questions/12201799/code-first-mvc-4-ef-5-many-to-many-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!