在实体框架中定义集合而不创建关系

时间:2014-09-28 11:55:36

标签: c# entity-framework

我有两个班级SongAlbumAlbum嵌套了歌曲集。但在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; }
}

2 个答案:

答案 0 :(得分:0)

好的,什么不起作用?你的模特看起来很好,除了剥夺你自己检查歌曲是否属于任何专辑的能力。

许多nad 1 - 许多关系被转换为单独的表,直到您在某些实例之间添加关系而不会丢失任何内存。是否有任何理由不向public Album Album {get;set;}添加:Album,您知道的是null吗?

答案 1 :(得分:0)

将您的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);
}
相关问题