База данных запросов для элементов, использующих разные идентификаторы для одного и того же объекта - PullRequest
0 голосов
/ 06 апреля 2020

Итак, я пытаюсь получить все «UserPhotos», где их «userId» == «FollowerId», у меня возникает проблема, когда существует более одного «FollowerId», мне нужно знать, как заставить его работать список «followerIds», чтобы пользователи могли получить «UserPhotos» всех «пользователей», за которыми они следят

    [HttpGet("u/{username}")]
    public async Task<IQueryable> GetSpecificFeed(string username)
    {
        var user = _context.Users.FirstOrDefault(x => x.Username == username);
        // Follower is the user that is being followed
        // Following is the user that is doing the following (so the current logged in user)

        var userId = user.Id;
        // This bit works and returns the correct userId

        var followerIds = _context.Follows.Where(x => x.FollowerId == userId);
        // This should return all of the 'FollowerIds' that the current user is following
        // This however doesn't do that, it just throws this error:
        // SQLite Error 1: 'no such column: x.UserId' (I don't know why)

        var feed = _context.UserPhotos.Where(x => x.UserId == userId);
        // This currently returns all of the 'UserPhotos' if their 'UserId' is equal to the 'UserId' 
        // (which is the id of the user that is logged in) -> This isn't what I want it to do
        // Once the 'followerIds' return the correct thing, it should then get the userPhotos where
        // The UserId == followerIds (followerIds will be an array, so it will have to check through
        // multiple values to get the whole 'feed'

        return feed;
    }

Так что это то, что я не могу понять

  1. Как получить FollowerIds (как массив (я думаю, что они должны быть массивом, но я не уверен))
  2. Как получить UserPhotos, когда у 'userId' есть несколько значений

(ps Я не уверен, что заголовок хорош, дайте мне знать, если я должен изменить его)

[EDIT]

Это следующий класс

 public class Follow
    {
        public int Id { get; set; }

        public int FollowingId { get; set; }
        // user that is following

        public int FollowerId { get; set; }
        // user that is being followed
    }

Класс пользователя (я удалил свойства, которые не релевантны в этом примере)

public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public ICollection<UserPhoto> UserPhotos { get; set; }
        public ICollection<Follow> Follows { get; set; }
    }

Класс userPhotos (я удалил свойства, которые не релевантны в этом примере)

public class UserPhoto
{
    public int Id { get; set; }
    public string photoUrl { get; set; }
    public int UserId { get; set; }
}

Это код, который показывает, как он должен работать, но это не так (это показывает, что я пытаюсь выполнить sh)

* 1 026 *

Ответы [ 2 ]

1 голос
/ 07 апреля 2020

Вы можете обратиться к следующему коду:

    [HttpGet("u/{username}")]
    public async Task<IQueryable> GetSpecificFeed(string username)
    {
        var user = _context.Users.FirstOrDefault(x => x.Username == username);
        var userId = user.Id;
        var photos = _context.UserPhotos;
        var followerIds = _context.Follows.Where(x => x.FollowerId == userId).Select(x => x.FollowingId).ToList();
        var feeds = _context.UserPhotos.Where(x => followerIds.Contains(x.UserId));
        return feeds;
    }
1 голос
/ 07 апреля 2020

Вы должны сначала запустить sql запрос. Вы можете использовать ToList () для этой цели в вашем случае.

[HttpGet("u/{username}")]
public async Task<IQueryable> GetSpecificFeed(string username)
{
    var user = _context.Users.FirstOrDefault(x => x.Username == username);

    var userId = user.Id;

    var followerIds = _context.Follows.Where(x => x.FollowerId == userId).ToList();

    var feeds = _context.UserPhotos.Where(x => followerIds.Contains( x.UserId ));

    return feeds;
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...