繁体   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