Postman 中的错误输出- ASP.NET LINQ联接

9bfwbjaz  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(120)

此控制器操作有问题:

public List<User> Index()
{
    var userList = 
        (from user in _context.Users 
        join photo in _context.Photos on user.Id equals photo.UserId 
        select new User
        { 
            Id = user.Id, 
            Name = user.Name, 
            Photos = user.Photos,
        }).ToList();

    return userList;
}

它多次返回同一用户,如下所示:
Postman result
这些是我的模特

public class User
{ 
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual List<Photo> Photos { get; set; } = new List<Photo>();
}

public class Photo
{ 
    [Key] 
    public int PhotoId { get; set; }

    public string Url { get; set; }

    [ForeignKey("User")] 
    public int UserId { get; set; }

    public User User { get; set; }
}

我尝试了不同的数据库命令语法,我希望每个用户只使用一次他们各自的数组或照片列表

bf1o4zei

bf1o4zei1#

您不需要连接,只需在投影中指定您需要的详细信息:

public List<User> Index()
{
    var userList = 
        (from user in _context.Users 
        select new User
        { 
            Id = user.Id, 
            Name = user.Name, 
            Photos = user.Photos,
        }).ToList();

    return userList;
}

相关问题