簡體   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