如果第二个表中有来自另一个表的Id的记录,则从第二个表中检索数据

时间:2013-12-28 14:48:08

标签: c# linq

我有2个上下文表,如果id相等,我想从中选择数据。

我想使用LINQ的流畅API来做到这一点。

我想检查Id中的Movie是否等于MovieId中的MovieReview,如果是,ReviewerName来自MovieReview和来自Name

Movie

表格是:

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

    [Range(1,10)]
    [Required]
    public int Rating { get; set; }

    [Required]
    [StringLength(1024)]
    public string Body { get; set; }

    [Display(Name="User Name")]
    [DisplayFormat(NullDisplayText="anonymous")]
    public string ReviewerName { get; set; }
    public int MovieId { get; set; }


public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Director { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public virtual ICollection<MovieReview> Reviews { get; set; }
}

非常感谢任何帮助。

到目前为止,我做了..甚至不确定我是否接近: var model =                 _db.Movies                 .Join(_db.Reviews,g =&gt; g.Id,u =&gt; u.MovieId,(g,u)=&gt; new {MovieReview = u,Movie = g})                 。(哪里(g =&gt; g.Movie                 select(r =&gt; new AdminReviewListViewModels                 {                     Id = g.Id,                     名称= g.Name,                     主任= g.Director,                     ReleaseDate = g.ReleaseDate,                     类型= g.Genre,                     CountOfReviews = g.Reviews.Count(),                     UserName = u.ReviewerName                 });

2 个答案:

答案 0 :(得分:0)

您可以使用:

context.Set<MovieReview>().Select(c=>new{c.ReviewerName, c.Movie.Name})

答案 1 :(得分:0)

如果您只需要一个包含MovieName和ReviewerName属性的匿名枚举,这应该可以。

using (var _db = new YourDbContext())
{
    var movies = _db.Movies;
    var movieReviews = _db.MovieReviews;

    var results = movies.Join(movieReviews, 
        m => m.Id,
        mr => mr.MovieId,
        (m, mr) => new { MovieName = m.Name, ReviewerName = mr.ReviewerName }).ToList();
}