xeraphim
xeraphim

Reputation: 4645

Entitiy Framework 6 - Save related entities

I have following entities:

public class Artist
{
    [Key]
    public string ArtistId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Genre> Genres { get; set; }
}

public class Genre
{
    [Key]
    public int GenreId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Artist> Artist { get; set; }
}

In my program I create some artists and want to save them:

using (var context = new ArtistContext())
{
    var artists = _fullArtists.Select(x => x.ToArtist());

    foreach (var artist in artists)
    {
        context.Artists.AddOrUpdate(artist);
    }

    context.SaveChanges();
}

The artists do have the property Genre. Unfortunately, when calling context.SaveChanges();, only the artists get saved the database and the genres doesn't.

Do I have to configure something special so that also the related entities (genre) get saved automatically to the database?

Thanks in advance

Edit: The .ToArtist() looks like this:

public static class ArtistExtensions
{
    public static Artist ToArtist(this FullArtistWrapper value)
    {
        if (value == null) { throw new ArgumentNullException(); }

        return new Artist
        {
            ArtistId = value.Id,
            Name = value.Name,
            Genres = new List<Genre>(value.Genres.Select(x => x.ToGenre()))
        };
    }
}

And the .ToGenre() like this:

public static class GenreExtensions
{
    public static Genre ToGenre(this string value)
    {
        return new Genre
        {
            Name = value
        };
    }
}

Upvotes: 2

Views: 765

Answers (2)

kjbartel
kjbartel

Reputation: 10581

I'm assuming that you're using proxy classes with lazy loading since you have the navigation properties set as virtual. The problem is that you're creating a new List<Genre> in ToArtist which will overwrite the proxy's collection. Try just adding the items to the existing collection instead.

The other problem may be that you aren't using proxies. Proxies will only be used for new entities if you use DbSet<T>.Create(). Otherwise you'll have to add all of the related entities to theDbContext` manually.

Upvotes: 1

Rafael Ribeiro
Rafael Ribeiro

Reputation: 188

If I understood, if you just want to save genres when the artists get saved on database, try to populate the genre's artist. For example.

List<Genres> lstGenres...

artist.Genres = lstGenres;

context.Entry(artist).State = EntityState.Added;

Hope that helps =)

Upvotes: 0

Related Questions