create table Person ( id int identity primary key, name nvarchar(30) ) create table PersonPersons ( PersonId references Person(id), ChildPersonId references Person(id) )
数据结构见上,
PersonPersons 存储了Person之间的关联关系
EntityFramework中的类设置如下:
class Person
{
public Guid PersonId { get; set; }
public virtual ICollection<Person> Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
ConfigureProducts(modelBuilder);
ConfigureMembership(modelBuilder);
modelBuilder.Entity<Person>()
.HasMany(entity => entity.Children)
.WithMany(child => child.Parent)
.Map(map =>
{
map.ToTable("PersonPersons");
map.MapLeftKey(left => left.PersonId, "PersonId");
map.MapRightKey(right => right.PersonId, "ChildPersonId");
});
}
(这个写法是从 http://stackoverflow.com/questions/5102930/how-to-do-many-to-many-with-the-same-table-with-ef4-code-first 搜索到的)
怎么实现查询 Person 的所有与之有联系的人呢?
我显示是这样实现的:
query = query.SelectMany(p=>p.Children )
.Where(p => p.PersonId == 需要查询的用户Id)
.OrderBy(c => c.PersonId );
记录条数是对的,但是查出来的全是 用户Id 的重复信息

正确的写法应该是什么?
有朋友建议这样写:
query = query.Include("Friends")
.Where(p => p.Id == userId)
.OrderBy(c => c.Id);
但是这样查询的数据就更离谱了!
有没有做过类似问题的朋友啊,请指点迷津,非常感谢!
