繁体   English   中英

使用 EF Core 获取两个不同表中存在的记录列表

[英]Getting list of records existing in two different tables using EF Core

我有一个人 class 具有以下属性

public class Persons
{
    public Guid Id {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public List<Connection> Connection {get; set;}
}

每个人都可以将另一个人添加为朋友。 当接受好友请求时,将创建两个人之间的连接。 连接 class 包含以下属性:

public class Connection
{
    public Guid UserId { get; set; }
    public Guid FriendId {get; set}
}

从 controller 我得到两个参数:firstPerson 的 id 和 secondPerson 的 id。 然后我调用 ConnectionLogic 方法。 这是方法(firstPerson 是接受请求的人, secondPerson 是发送请求的人):

public async Task ConnectionLogic(Guid firstPerson, Guid secondPerson)
{
    Connection con = new() 
    {
        User = firstPerson;
        Friend = secondPerson;
    };

    await repo.CreateConnection(con);
}

这是存储库代码

public async Task CreateConntection(Connection con)
{
    Context.Connections.Add(con);
    await Context.SaveChangeAsync();
} 

现在我想获取所有用户朋友的列表以及他们的名字和姓氏。 这是我写的代码。

public async Task<List<Person>> GetAllConnections(Guid id)
{
    List<Person> firends = new();

    List<Guid> friendsId = await Context.Connections
    .Where(x => x.User == id)
    .Select(x => x.Friend)
    .ToListAsync();

    foreach (var item in friendsId)
    {
        firends.Add(Context.Persons.Where(id => id.Id == item).Select(x => new Person {FirstName == x.FirstName, LastName == x.LastName}).FirstOrDefault());    
    }

    return friends;
}

但我知道当列表变得越来越大时,它会导致巨大的性能问题。 获取给定用户 id 的所有朋友的最佳方法是什么?

是否有理由不在连接 class 上放置导航属性?

为用户和朋友添加导航属性

public class Connection
{
    public Guid UserId { get; set; }
    public Guid FriendId {get; set}
    public Person User { get; set; }
    public Person Friend { get; set; }
}

更新 GetAllConnections

public async Task<List<Person>> GetAllConnections(Guid id)
{
    return await Context.Connections
        .Where(c => c.UserId == id)
        .Select(c => c.Friend)
        .ToListAsync();
}

然后它只是对数据库的一个查询,而不是对每个“FriendId”的单独查询。

准确复制您的场景(只需获取名字和姓氏)

public async Task<List<Person>> GetJustNameOfAllConnections(Guid id)
{
    return await Context.Connections
        .Where(c => c.UserId == id)
        .Select(c => new Person
        {
            FirstName = c.Friend.FirstName,
            LastName = c.Friend.LastName
        }).ToListAsync();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM