LINQ to entities - Seleccionar todos los de los amigos del Usuario y la Charla entre ellos

0

Pregunta

¿Cómo puedo Seleccionar todos los amigos del usuario conectado en ese momento y los Chats Privados (Id de Chat) entre el usuario y sus amigos? Soy capaz de obtener el de los amigos del usuario, pero estoy teniendo problemas para también conseguir la Charla entre ellos.

            // Select all the User's friends and the chat (Id) between them
            var friends = await _context.Friendships // Get the Friendships
                .Include(x => x.Friend).ThenInclude(x => x.ChatUsers).ThenInclude(x => x.Chat)
                .Where(x => x.Status == StatusCode.Accepted && x.ApplicationUserId == userId)
                .Select(x => x.Friend)
                .ToListAsync();

Mesa de amistad

    public class Friendship
    {
        // The primary keys/foreign keys of the associated tables
        public string ApplicationUserId { get; set; }
        public string ApplicationFriendUserId { get; set; }

        // Reference to the user that has the friend
        public User ApplicationUser { get; set; }

        // Reference to the friend
        public User Friend { get; set; }

        // The status of the friendship
        public StatusCode Status { get; set; }
    }

Tabla de usuario

    public class User : IdentityUser
    {
        // Reference to all user's chats
        public ICollection<ChatUser> ChatUsers { get; set; }

        // Reference to all the user's friendships
        public ICollection<Friendship> UsersFriendships { get; set; }

        // Reference to all the friend's friendships (their point of view)
        public ICollection<Friendship> FriendsFriendships { get; set; }
    }

ChatUser tabla

    public class ChatUser
    {
        // The primary key/foreign keys of the associated tables
        public int ChatId { get; set; }
        public string UserId { get; set; }

        // The role that the User can be
        public UserRole Role { get; set; }

        // Reference to the chat
        public Chat Chat { get; set; }

        // Reference to the user
        public User User { get; set; }
    }

Chat

    
    public class Chat
    {
        // The primary key
        public int Id { get; set; }

        // The chat's name
        public string Name { get; set; }

        // The chat type, e.g room, private
        public ChatType Type { get; set; }

        // Reference to all the Chat's Users
        public ICollection<ChatUser> ChatUsers { get; set; }
    }

Gracias

1

Mejor respuesta

1

Esta consulta:

var friends = await _context.Friendships // Get the Friendships
    .Include(x => x.Friend).ThenInclude(x => x.ChatUsers).ThenInclude(x => x.Chat)
    .Where(x => x.Status == StatusCode.Accepted && x.ApplicationUserId == userId)
    .Select(x => x.Friend)
    .ToListAsync();

... carga el usuario de los amigos con los amigos correspondiente chats que incluiría los chats no con el usuario actual.

Con la estructura de dominio de los chats y las amistades que se ve bastante difícil de tratar y conectarlos de una manera significativa. Es probable que sea posible con un simple enfoque de dos pasos:

var friendIds = _context.Users
    .Where(x => s.UserId == userId)
    .SelectMany(x => x.UsersFriendships.Where(f => f.Status == StatusCode.Accepted).Select(f => f.ApplicationFriendUserId))
    .ToList(); // Get all accepted Friend IDs.


 var chats = _context.Chats
     .Where(x => x.ChatUsers.Any(cu => cu.UserId) && x => x.ChatUsers.Any(cu => friendIds.Contains(cu.UserId)
     .Select(x => new 
     {
         Chat = x,
         Friends = x.ChatUsers.Where(cu => friendIds.Contains(cu.UserId)).Select(cu => cu.User).ToList()
      }).ToList();

Los Chats están relacionadas con dos o más usuarios, y que no se limitan/vinculado a las amistades.

Joe podía ser amigos con Sam, Jane, y Juan y tiene las siguientes charlas activo:

Chat 1: Joe <-> Sam

Charla 2: Joe <-> Jane

Charla 3: Joe <-> Jane <-> Sam

Charla 4: Joe <-> Frank

Chat 5: Joe <-> Franco <-> Sam

Nos gustaría Chats 1, 2, 3, y 5 devuelto. No hay charlas con Juan, y no nos preocupamos de la charla con Frank, pero sí les importa el uno con Frank & Sam Sam es un amigo. El objetivo sería identificar que los chats de que Joe está participando en uno o más de sus amigos. Para cada partido se devuelve el chat y Amigos en la actualidad también en esa charla.

La salvedad de que el enfoque de dos pasos es que se supone que el amigo de la lista seguiría siendo bastante pequeña, no lo suficientemente grande para superar el IN() la lista que se genera para conseguir la coincidencia de los Chats.

2021-11-23 04:50:49

En otros idiomas

Esta página está en otros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Slovenský
..................................................................................................................