2014-09-28 61 views
0

我有两个类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; } 
} 
+0

你没有一个主键。 Id属性每次都是一个新字符串。 – LiverpoolsNumber9 2014-09-28 12:21:52

+0

不确定为什么你会把字符串当作关键字? – 2014-09-28 13:26:37

回答

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); 
} 
+0

不应该是虚拟的专辑吗?也可能不是modelBuilder.Entity ().HasOptional(c => c.Album).WithMany(t => tSong) – 2014-09-28 15:33:32

+0

@kirsteng:如果你想使用延迟加载,它应该是虚拟的。 – Masoud 2014-09-28 15:35:24

+0

@ kirsteng:是的,你是对的,我更新了答案。 – Masoud 2014-09-28 15:42:24

0

好的,什么是不工作?你的模型看起来很好,除了让你无法检查宋是否是任何专辑的一部分。

许多许多nad一对多关系被翻译成单独的表,直到你添加某些实例之间的关系,你不会失去任何内存。是否有任何理由不添加:public Album Album {get;set;}Album,有类似null的东西你知道吗?