簡體   English   中英

在實體框架中定義集合而不創建關系

[英]Define collection in entity framework without creating relationship

我有兩個班SongAlbum Album有嵌套的歌曲集。 但是在EF中,我必須在兩者之間建立關系。 但是Song可以是單曲,也可以沒有Album 所以我想在數據庫中創建類似的東西。

public class Song:IEntity
{
    public Song()
    {
        Id = Guid.NewGuid().ToString();
    }
    public string Id { get; set; }
    public string Artist { get; set; }
    public string Title { get; set; }

}

public class Album:IEntity
{
    public Album()
    {
        Id = Guid.NewGuid().ToString();
    }
    public string Id { get; set; }
    public string Artist { get; set; }
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public virtual ICollection<Song> Songs { get; set; }
}

好的,什么不起作用? 除了使自己無法檢查Song是否屬於任何專輯之外,您的模型看起來還不錯。

多對多1對多關系將轉換為單獨的表,直到您在某些實例之間添加關系為止,您才不會丟失任何內存。 是否有任何理由不添加: public Album Album {get;set;}Album ,您知道類似null內容嗎?

將您的Song類更新為:

public class Song:IEntity
{
    public Song()
    {
        Id = Guid.NewGuid().ToString();
    }
    public virtual Album Album { get; set; }. //add this line
    public string Id { get; set; }
    public string Artist { get; set; }
    public string Title { get; set; }
}

並在DbContext定義以下映射:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     modelBuilder.Entity<Song>() 
            .HasOptional(c => c.Album) 
            .WithMany(t => t.Songs);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM