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);
但是這樣查詢的數據就更離譜了!
有沒有做過類似問題的朋友啊,請指點迷津,非常感謝!
