代码优先MVC 4 EF 5多对多联接 [英] Code First MVC 4 EF 5 many-to-many Join
问题描述
过去的几天我一直在为此苦苦挣扎,似乎无法弄清楚.我在MVC 4和EF 5中使用了代码优先方法.我通过流畅的API建立了多对多关系.这是示例代码:
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; }
}
用户类别:
public class User
{
public User()
{
}
/// <summary>
/// Unique Id in the system
///</summary>
[Key]
public long Id { get; set; }
public List<Class> Classes { get; set; }
}
流利的API在这里:
modelBuilder.Entity<Class>().HasMany(m => m.Teachers).WithMany(t => t.Classes).Map(m =>
{
m.ToTable("ClassTeachers");
m.MapLeftKey("ClassId");
m.MapRightKey("UserId");
});
怎么回事:
EF正在创建ClassTeachers表,当我选择所有类时,将按预期接收数据.这些班级在返回的数据中具有正确的教师.
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.
我需要帮助的地方
我正试图返回所有具有特定老师的班级.我正在尝试这样的事情:
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 };
但是,我没有找回正确的数据.通常,我可以在它们之间加入第三个表以获取所需的结果,但是,EF Code First方法不提供此表.我真的很茫然...
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...
谢谢.
推荐答案
尝试一下:
var classesTeachers = from c in data.Classes
where c.Teachers.Any(t => t.Id == mockUser.Id)
select c;
这篇关于代码优先MVC 4 EF 5多对多联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!