ASP.NET MVC:如何通过ID获取其他模型的项目列表
我有两个模型: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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
鉴于您已经有一个
列表&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 uselinq
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();
yourContext将是您数据库的实例。
而youruserid可能是您的模型。
yourContext would be the instance of your Database.
And yourUserId could be your Model.User.Id, depending on how you have done it