Question

I'm not using code first, I created a table called artists with an ID and name field, a table called albums with an id and title field and a junction_artists_albums table with artist_id and album_id.

Here are my model/context classes:

Artist:

    public class Artist
{
    public int Id { get; set; }
    public string ArtistName { get; set; }

    public ICollection<Album> albums { get; set; }
}

Album:

    public class Album
{
    public int Id { get; set; }
    public string AlbumName { get; set; }

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


}

MusicDBContext:

    public class MusicDBContext : DbContext
{
    public MusicDBContext() { }

    public DbSet<Artist> Artists { get; set; }
    public DbSet<Album> Albums { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Album>().HasMany<Artist>(a => a.artists).WithMany(a => a.albums);
    }
}

This doesn't work because the junction table isn't being filled in. Excuse me if this is a stupid question but I'm very new to Entity Framework

Était-ce utile?

La solution

No, is not that stupid. And the solution is easy.

When dealing with many to many relationships you don't need to specify a junction table explicitly unless there is a relationship field. For example, Albums produced by an artist, there you may have production date or something.

What you need to do here is to change a bit what you have done in this way

public class Artist
{
    public int Id { get; set; }
    public string ArtistName { get; set; }

    #region Navigation Properties
    public virtual ICollection<Album> Albums { get; set; }
    #endregion
}

public class Album
{
    public int Id { get; set; }
    public string AlbumName { get; set; }

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

I don't know exactly what this means, but you can remove the OnModelCreating event override

Note the navigation properties and foreign key specifications in EF Code first are always virtual properties.

When there is many to many relationships, you just need to specify related navigation properties and EF will take charge of the rest and the junction table will be created with both primary keys in it. If, as I told you before, there are some relationship fields, you need to create the Junction table by hand end explicitly create a class with both keys and the relationship fields.

there is something in EF called conventions, and is just a set of naming conventions you'll be getting used to and some decorators that may help you in explicitly set foreign keys and more.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top