简体   繁体   English

在单个查询中使用表和外键表中的数据

[英]Using data from a table and foreign key table in single query

hard to explain from title, hopefully this description helps explain the situation. 很难从标题中进行解释,希望此描述有助于解释情况。 I have a music app where a user can create a playlist. 我有一个音乐应用程序,用户可以在其中创建播放列表。 So I set up two tables. 所以我建立了两个表。

One called Playlists (columns: PlaylistID, PlaylistName, CreatorID) and another called PlaylistSongs (columns: PlaylistSongID, PlaylistID, and SongID). 一个称为Playlists (列:PlaylistID,PlaylistName,CreatorID),另一个称为PlaylistSongs (列:PlaylistSongID,PlaylistID和SongID)。 I have a foreign key connection between the PlaylistID columns. 我在PlaylistID列之间有一个外键连接。

I want to display a list of playlists on the home page, each one looks like this: 我想在主页上显示一个播放列表列表,每个列表如下所示: 在此处输入图片说明

I can pull the playlist name from Playlist table and display properly....easy. 我可以从“ Playlist表中提取播放列表名称,并正确显示。 The issue I am having is figuring out how to display the metadata such as the artists (Sasha Sloan ODESZA etc) which I can obtain from the SongID from the PlaylistSongs table which is connected by foreign key. 我遇到的问题是弄清楚如何显示元数据,例如艺术家(Sasha Sloan ODESZA等),这些元数据可以从通过外键连接的PlaylistSongs表的SongID中获取。

Here's what I have right now: 这是我现在所拥有的:

Controller 调节器

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

    return View(model);
}

Model: 模型:

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

CSHTML: 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 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 EntityDataAccess.cs

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

So I essentially have a model with this Playlist info: 因此,我基本上有一个具有此Playlist信息的模型:

  • PlaylistID PlaylistID
  • PlaylistName PlaylistName
  • CreatorID 的CreatorID

I need to use each unique PlaylistID to access the songs in the PlaylistSongs table that have that PlaylistID so I can display on screen. 我需要使用每个唯一的PlaylistID来访问PlaylistSongs表中具有该PlaylistID的歌曲,以便可以在屏幕上显示。 Does that make sense? 那有意义吗?

EDIT: Added call to context and corresponding class 编辑:添加了对上下文和相应类的调用

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

Unearth Entities: 挖掘实体:

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; }
    }

Refer to Microsoft's article: Entity Framework Loading Related Entities 请参阅Microsoft的文章: 实体框架加载相关实体

Assuming your data context is correct, use the Include to bring in the related data, like: 假设您的数据上下文正确,请使用Include引入相关数据,例如:

return Context.Playlists.Include("PlaylistSongs").Take(count).ToList();

BTW: For clarity, I would rename some of your fields. 顺便说一句:为清楚起见,我将重命名您的某些字段。 For example, primary key (PK) field names need not be prefixed with the name of the table. 例如,主键(PK)字段名称不必以表名作为前缀。 It gets confusing. 令人困惑。 Just name your PK field "Id". 只需将您的PK字段命名为“ Id”即可。 When referring to a key field from within a related table, then use the table name. 从相关表中引用键字段时,请使用表名。 For example, to make a one-to-many relationship between Playlists, and PlaylistSongs, a field named PlaylistId would exist in the table PlaylistSongs. 例如,要在播放列表和播放列表歌曲之间建立一对多关系,表PlaylistSongs中将存在一个名为PlaylistId的字段。

Regarding the building of a model, take a look at Microsoft's documents Creating a Model and Foreign Key Constraints . 关于模型的构建,请查看Microsoft的文档“ 创建模型外键约束” The first provides a link to github repo of sample code. 第一个提供了到示例代码的github回购的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM