在单个查询

时间:2018-03-03 23:14:31

标签: c# asp.net entity-framework

很难从标题中解释,希望这种描述有助于解释这种情况。我有一个音乐应用程序,用户可以在其中创建播放列表。所以我设置了两个表。

一个名为Playlists(列:PlaylistID,PlaylistName,CreatorID),另一个名为PlaylistSongs(列:PlaylistSongID,PlaylistID和SongID)。我在PlaylistID列之间有一个外键连接。

我想在主页上显示播放列表列表,每个播放列表如下所示: enter image description here

我可以从Playlist表中提取播放列表名称并正确显示....轻松。我遇到的问题是如何显示如何显示元数据,如艺术家(Sasha Sloan ODESZA等),我可以从通过外键连接的PlaylistSongs表中的SongID获取。

这就是我现在所拥有的:

控制器

public ActionResult Playlists()
{
    var model = new HomePlaylistViewModel();
    model.Playlists = EntityDataAccess.GetFeaturedPlaylistsByCount(6);

    return View(model);
}

型号:

public class HomePlaylistViewModel
{
    public List<Playlist> Playlists { get; set; }
    public List<PlaylistSong> PlaylistSongs { get; set; }
    public List<Album> Albums { get; set; }
}

CSHTML:

<div class="playlists-container">

            @foreach (var item in Model.Playlists)
            {
                <div class="playlist-album">
                    <div class="album-grad"></div>
                    <a href="#">
                        <h1>
                            @item.PlaylistName
                        </h1>

                        <div class="playlist-desc-container">
                                <h4 class="playlist-desc">Featuring: INSERT ARTIST NAMES HERE</h4>
                                <h4 class="playlist-creator"> Songs &#8226; Curated by
                           </h4>
                        </div>

                        <img src="https://ucarecdn.com/6d669906-60df-4f26-bf80-f11eef3bd019/-/format/jpeg/-/quality/lightest/" class="playlist-album-art">
                    </a>
                    <button class="ui button playlist-listen">LISTEN</button>
                    <button class="ui button playlist-collect"><i class="material-icons">playlist_add</i></button>
                </div>
            }

Playlist.cs

public partial class Playlist
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Playlist()
    {
        this.PlaylistSongs = new HashSet<PlaylistSong>();
    }

    public int PlaylistID { get; set; }
    public string PlaylistName { get; set; }
    public int CreatorID { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PlaylistSong> PlaylistSongs { get; set; }
}

EntityDataAccess.cs

public static List<Playlist> GetFeaturedPlaylistsByCount(int count)
        {
            using (var Context = GetContext())
            {
                return Context.Playlists.Take(count).ToList();
            }
        }

所以我基本上有一个带有Playlist信息的模型:

  • PlaylistID
  • PlaylistName
  • 的CreatorID

我需要使用每个唯一的PlaylistID来访问PlaylistSongs表中具有该PlaylistID的歌曲,以便我可以在屏幕上显示。这有意义吗?

编辑:添加了对上下文和相应类

的调用
public static UnearthEntities GetContext()
        {
            var context = new UnearthEntities();
            context.Configuration.ProxyCreationEnabled = false;
            return context;
        }

发掘实体:

public partial class UnearthEntities : DbContext
    {
        public UnearthEntities()
            : base("name=UnearthEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<AccountInfo> AccountInfoes { get; set; }
        public virtual DbSet<Album> Albums { get; set; }
        public virtual DbSet<AlbumTag> AlbumTags { get; set; }
        public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
        public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
        public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
        public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
        public virtual DbSet<DownloadHistory> DownloadHistories { get; set; }
        public virtual DbSet<Song> Songs { get; set; }
        public virtual DbSet<Spotlight> Spotlights { get; set; }
        public virtual DbSet<Video> Videos { get; set; }
        public virtual DbSet<FeaturedAlbum> FeaturedAlbums { get; set; }
        public virtual DbSet<Key> Keys { get; set; }
        public virtual DbSet<SongPlayDaily> SongPlayDailies { get; set; }
        public virtual DbSet<Favorite> Favorites { get; set; }
        public virtual DbSet<License> Licenses { get; set; }
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<Playlist> Playlists { get; set; }
        public virtual DbSet<PlaylistSong> PlaylistSongs { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

请参阅Microsoft的文章:Entity Framework Loading Related Entities

假设您的数据上下文正确无误,请使用Include引入相关数据,例如:

return Context.Playlists.Include("PlaylistSongs").Take(count).ToList();
顺便说一句:为清楚起见,我会重命名你的一些字段。例如,主键(PK)字段名称不需要以表的名称为前缀。这让人很困惑。只需命名您的PK字段&#34; Id&#34;。在引用相关表中的键字段时,请使用表名。例如,要在播放列表和PlaylistSongs之间建立一对多关系,PlaylistSongs表中将存在名为PlaylistId的字段。

关于模型的构建,请查看Microsoft的文档Creating a ModelForeign Key Constraints。第一个提供了一个指向示例代码的github repo的链接。