EntityFramework的奇怪问题,国外网站也无解


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);

  但是这样查询的数据就更离谱了!

有没有做过类似问题的朋友啊,请指点迷津,非常感谢!

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM