实体框架显示错误或更少的数据

时间:2014-04-02 21:20:01

标签: .net database entity-framework

我正在使用ef代码

public static void run()
{
    using (var context = new EF6RecipesEntities1())
    {
        // add an artist with two albums
        var artist = new Artist { FirstName = "Alan", LastName = "Jackson" };
        var album1 = new Album { AlbumName = "Drive" };
        var album2 = new Album { AlbumName = "Live at Texas Stadium" };
        artist.Albums.Add(album1);
        artist.Albums.Add(album2);
        context.Artists.Add(artist);
        // add an album for two artists
        var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };
        var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };
        var album = new Album { AlbumName = "Honkytonk University" };
        artist1.Albums.Add(album);
        artist2.Albums.Add(album);
        context.Albums.Add(album);
        context.SaveChanges();
    }

    using (var context = new EF6RecipesEntities1())
    {
        Console.WriteLine("Artists and their albums...");
        var artists = context.Artists;
        foreach (var artist in artists)
        {
            Console.WriteLine("{0} {1}", artist.FirstName, artist.LastName);
            foreach (var album in artist.Albums)
            {
                Console.WriteLine("\t{0}", album.AlbumName);
            }
        }
        Console.WriteLine("\nAlbums and their artists...");
        var albums = context.Albums;
        foreach (var album in albums)
        {
            Console.WriteLine("{0}", album.AlbumName);
            foreach (var artist in album.Artists)
            {
                Console.WriteLine("\t{0} {1}", artist.FirstName, artist.LastName);
            }
        }
    }
}

它应该显示

Artists and their albums...
Alan Jackson
    Drive
    Live at Texas Stadium
Tobby Keith
    Honkytonk University
Merle Haggard
    Honkytonk University

Albums and their artists...
Drive
    Alan Jackson
Live at Texas Stadium
    Alan Jackson
Honkytonk University
    Tobby Keith
    Merle Haggard  

但我很喜欢

Artists and their albums...
Alan Jackson
        Drive
        Live at Texas Stadium

Albums and their artists...
Drive
        Alan Jackson
Live at Texas Stadium
        Alan Jackson
Honkytonk University

1 个答案:

答案 0 :(得分:0)

我刚刚改变了这一行

    context.Albums.Add(album);

            context.Artists.Add(artist1);
            context.Artists.Add(artist2);

现在它正在插入并显示准确的数据