繁体   English   中英

Entity Framework和Many-to-Many关系,控制中间表列名

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

我试图围绕与Code-First映射的多对多关系。

如果我有一个可以有很多GenresAlbum类(反之亦然),我理解我需要一个中级表,实体框架会自动为我做这个。 但是,我想更多地控制Intermediate表,所以我自己创建一个,主要原因是我希望能够将行标记为从前端删除并将其保留在数据库中。

为我的所有类执行此操作,我创建了一个继承自的BaseObject(我删除了许多注释和其他代码以简化此帖子):

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; }
}

之后我们有AlbumsGenres类:

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; }
}

最后是AlbumsGenres中级班:

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; }
    */
}   

我有的问题; 有没有办法告诉EF使用不同的列名如Album创建Album_Oid

如果提供了简短的解释(或链接),我会接受“只是不要担心”的答案。

您可以控制中间表,通常我使用显式映射,但以下内容适用于CodeFirst:

在相册中,你想要一个List<Genre> (不是AlbumGenre)在流派中,你想要一个List<Album>

在您的上下文中,为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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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