简体   繁体   中英

Entity Framework and Many-to-Many relationships, controlling the Intermediate table column names

I'm trying to wrap my head around a Many-to-Many relationship with Code-First mapping.

If I have an Album Class that can have many Genres (and vice-versa), I understand that I need to have an Intermediate table and Entity Framework will automatically do that for me. However, I would like a little more control over the Intermediate table, so I am creating one myself, the main reason is that I would like to be able to mark the row as deleted from the front-end and leave it in the database.

To do this for all my Classes I have created a BaseObject that they are Inherit from (I've removed many of the Annotations and other code to simplify this post):

public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Oid { get; set; 
    public DateTime DateCreated { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime? DeletedDate { get; set; }
}

After that we have the Albums and Genres Classes:

public class Album : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Albums { get; set; }
}

public class Genre : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Genres { get; set; }
}

Finally the AlbumsGenres Intermediate Class:

public class AlbumsGenres : BaseObject
{
    // Left blank because EF will create "Album_Oid" and "Genre_Oid" columns
    // Tried the below code, but EF still created it's own Columns
    /*
        public Guid Album { get; set; }
        public Guid Genre { get; set; }
    */
}   

The questions that I have; Is there a way to tell EF to create Album_Oid with a different Column Name like Album ?

I would accept an answer of "Just don't worry about it", if a brief explanation (or link) was provided.

You can control the intermediate table, Normally I use explicit mapping but the following works with CodeFirst:

In Album, you want a List<Genre> (not AlbumGenre) In Genre, you want a List<Album>

In your context, add the following override for OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Album>()
        .HasMany(a => a.Genres)
        .WithMany(g => g.Albums)
        .Map(x =>
        {
            x.MapLeftKey("AlbumId");
            x.MapRightKey("GenreId");
            x.ToTable("AlbumGenres");
        });

    base.OnModelCreating(modelBuilder);
}

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