方法使用join和where子句从2个表返回ViewModel

时间:2016-03-26 20:39:30

标签: c# sql asp.net-mvc linq lambda

我正在研究一种方法,我有两个模型,艺术家和专辑,我想根据属于艺术家的ArtistID字段显示属于艺术家的所有专辑,并提供两种模型的信息和专辑,这就是我创建ViewModel的原因。我正在一个名为Operations的单独类中使用我的方法与模型和控制器分离,我正在使用lambda表达式,我不知道如何为ArtistID = id参数设置“where”条件。你知道怎么做吗?

这些是模特:

public class Artist
{
    public int ArtistID { get; set; }
    [Display(Name ="Artist name")]
    public string Name { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public virtual List<Album> Albums { get; set; }
}

public class Album
{
    public int AlbumID { get; set; }
    public string AlbumName { get; set; }
    public virtual Artist Artist { get; set; }
    public int ArtistID { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0: dd/MM/yyyy}")]
    [Display(Name ="Date created")]
    public DateTime DateCreated { get; set; }

}

这是ViewModel:

public class ArtistAlbumVM
{
    public int ArtistAge { get; set; }
    public string ArtistName { get; set; }
    public string ArtistLastName { get; set; }
    public DateTime AlbumDate { get; set; }
    public string AlbumName { get; set; }
}

这就是我正在谈论的方法,我不知道如何设置“where”条件ArtistID = id

public class Operations
{
    MusicStoreDbContext db = new MusicStoreDbContext();
    public List<ArtistAlbumVM> GetAlbumsByArtist(int id)
    {
        var list = db.Albums.Join(db.Artists, al => al.ArtistID, ar => ar.ArtistID,
            (al, ar) => new ArtistAlbumVM {
                ArtistAge = ar.Age,
                ArtistName =ar.Name,
                ArtistLastName = ar.LastName,
                AlbumDate = al.DateCreated,
                AlbumName = al.AlbumName
            });
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ where子句。

public List<ArtistAlbumVM> GetAlbumsByArtist(int id)
{
  return db.Albums.Where(s=>s.ArtistId==id)
                  .Select(x=> new ArtistAlbumVm 
                         { 
                             ArtistAge = x.Artist.Age,
                             ArtistName =x.Artist.Name,
                             ArtistLastName = x.Artist.LastName,
                             AlbumDate = x.DateCreated,
                             AlbumName = x.AlbumName
                          }).ToList();
}