ASP.NET MVC:如何通过ID获取其他模型的项目列表

发布于 2025-02-09 13:31:11 字数 448 浏览 3 评论 0原文

我有两个模型:picture.cs

    public class Picture
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Link { get; set; }
}

and user.cs

    public class User
{
    public int Id { get; set; }
    public virtual List<Picture> Pictures { get; set; }
}

list&lt; picture&gt;中,我想用userId =用户ID获得所有图片,但代替了I在数据库中获取所有图片。

I have two models: Picture.cs

    public class Picture
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Link { get; set; }
}

And User.cs

    public class User
{
    public int Id { get; set; }
    public virtual List<Picture> Pictures { get; set; }
}

In a List<Picture>, I want to get all pictures with UserId = User Id, but instead of it I get all pictures in the database that I have.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巾帼英雄 2025-02-16 13:31:11

鉴于您已经有一个列表&lt; picture&gt; Allpictures,您只需使用linq根据用户ID列出的列出:

list&lt; picture&gt; pictureforuser = allpictures.where(x =&gt; x.userid == someUserid).tolist()

,或者您可以直接从数据库中查询它们,如@javi建议:

list&lt; lict&lt; picture&gt; pictureforuser = yourdbcontext.pictures.pictures.where(p =&gt; p.userid == someuserid).tolist();>

Given you already have a List<Picture> allPictures, you would simply use linq to filter the listed based on userid:

List<Picture> picturesForUser = allPictures.Where(x => x.UserId == someUserId).ToList()

or you can query them directly from the database as @Javi suggested:

List<Picture> picturesForUser = yourDbContext.Pictures.Where(p => p.UserId == someUserId).ToList();

捂风挽笑 2025-02-16 13:31:11
List<Picture> myList = yourContext.Picture.Where(p => p.UserId == yourUserId).ToList();

yourContext将是您数据库的实例。
而youruserid可能是您的模型。

List<Picture> myList = yourContext.Picture.Where(p => p.UserId == yourUserId).ToList();

yourContext would be the instance of your Database.
And yourUserId could be your Model.User.Id, depending on how you have done it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文