简体   繁体   English

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

[英]Define collection in entity framework without creating relationship

I have two classes Song and Album . 我有两个班SongAlbum Album has nested collection of songs. Album有嵌套的歌曲集。 But in EF I have to create relationships between. 但是在EF中,我必须在两者之间建立关系。 But Song can be single or without Album . 但是Song可以是单曲,也可以没有Album So I want create something like that in database. 所以我想在数据库中创建类似的东西。

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; }
}

Ok, and what is not working? 好的,什么不起作用? Your model looks fine besides depriving yourself from ability to check if Song is part of any album or not. 除了使自己无法检查Song是否属于任何专辑之外,您的模型看起来还不错。

Many-Many nad 1-Many relationships are translated into seperate tables, until you add relationship between certain instances you don't lose any memory. 多对多1对多关系将转换为单独的表,直到您在某些实例之间添加关系为止,您才不会丢失任何内存。 Is there any reason why not to add: public Album Album {get;set;} to the Album , there is something like null you know? 是否有任何理由不添加: public Album Album {get;set;}Album ,您知道类似null内容吗?

Update your Song class to: 将您的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; }
}

And define following mapping in your DbContext : 并在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