使用Entity Framework代码 - 首先假设我有类:
class Person
{
public Person()
{
Houses = new List<House>();
}
public Guid PersonId { get; set; }
public string Name { get; set; }
public virtual List<House> Houses { get; set; }
}
public House
{
public Guid HouseId { get; set; }
public string Address { get; set; }
}
然后我创建了一个只暴露一个实体的上下文。然后我用多对多的关系映射它们。
public class PersonContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasMany(p => p.Houses)
.WithMany()
.Map(m =>
{
m.ToTable("PeopleHouses");
m.MapLeftKey("PersonId");
m.MapRightKey("HouseId");
}
}
}
运行时,Entity Framework会创建连接表。
我的问题是如何创建LINQ查询以检索属于单个人的房屋? (使用PersonId)
答案 0 :(得分:3)
我没有看到你的问题...它有一个导航属性。
var houses = People.First(n => /* select your person */).Houses;
答案 1 :(得分:0)
var houses = Peoples.Where(p => p.PersonId == YourPersonIdHere).Select(p => p.Houses);