简体   繁体   中英

How to get reference for child entries of the parent in one-to-many relationship?

I implement the one-to-many relationships with SQLite and Entity Framework Core. I have 2 tables: the table Albums representing the "one" and table Songs representing "Many". here's my databaseContext with Album and Song model classes:

namespace SQLite_test2
{
    public class DatabaseContext : DbContext
    {
        public DbSet<Album> albums { get; set; }
        public DbSet<Song> songs { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
        {
            dbContextOptionsBuilder.UseSqlite("Data Source =database.db");
        }
    }


    public class Album
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Artist { get; set; }
        public List<Song> Songs { get; set; } = new List<Song>();

    }
    public class Song
    {
        public int Id { get; set; }
        public string Songname { get; set; }

        public int AlbumId { get; set; }

        public Album Album { get; set; }
    }

}

Now let's add 1 album and 2 related songs:

    class Program
    {
        static void Main(string[] args)
        {
            using (var databaseContext = new DatabaseContext())
            {
                Album myAlbum = new Album() { Title = "Toxicity", Artist = "System of A Down" };
                Song mySong1 = new Song() { Songname = "Chop Suey" };
                Song mySong2 = new Song() { Songname = "Psycho" };
                myAlbum.Songs.Add(mySong1);
                myAlbum.Songs.Add(mySong2);

                databaseContext.albums.Add(myAlbum);
                databaseContext.songs.Add(mySong1);
                databaseContext.songs.Add(mySong2);
                databaseContext.SaveChanges();
            }
        }
    }

Seems to be working ok:

[ 在此处输入图像描述 ] 在此处输入图像描述 1

When I try to iterate through the songs in the album it doesn't work:

class Program
{
    static void Main(string[] args)
    {

        using (var databaseContext = new DatabaseContext())
        {
            //Album myAlbum = new Album() { Title = "Toxicity", Artist = "System of A Down" };
            //Song mySong1 = new Song() { Songname = "Chop Suey" };
            //Song mySong2 = new Song() { Songname = "Psycho" };
            //myAlbum.Songs.Add(mySong1);
            //myAlbum.Songs.Add(mySong2);

            //databaseContext.albums.Add(myAlbum);
            //databaseContext.songs.Add(mySong1);
            //databaseContext.songs.Add(mySong2);
            //databaseContext.SaveChanges();

            var myAlbum = databaseContext.albums.Find(5);
            if (myAlbum.Songs.Count == 0)
            {
                //no songs referenced
                Console.WriteLine("no songs referenced");
            }
            foreach (var item in myAlbum.Songs)
            {
                Console.WriteLine("Artist: {0}, Album name: {1} song: {2}", myAlbum.Artist, myAlbum.Title, item.Songname);
            }


        }
    }
}

How do I get the .Songs using Entity Framework Core?

Bonus question: even when I delete the table, the primary key increment persists. Can I delete the table with resetting the primary key back to 1 without dropping the table completely and making it anew?

Try explicitly including the songs:

var myAlbum = databaseContext.albums.Include((x) => x.Songs).Where((album) => album.Id == 5).FirstOrDefault();

As for the bonus-question. There is no direct way in ef to reseed the primary key. Although you can use a direct sql statement like this (after deleting the data):

efcore 3.x

databaseContext.Database.ExecuteSqlRaw("DBCC CHECKIDENT('Albums', RESEED, 0)")

other ef

databaseContext.Database.ExecuteSqlCommand("DBCC CHECKIDENT('Albums', RESEED, 0)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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