简体   繁体   中英

Entity Framework 6.0 One to Many relationship is not working

I try to use Entity Framework with code first and fluent api to implement a one to many relationship

On the one side, I have the ClassDefinitionEntity class :

 public class ClassDefinitionEntity{   

    public string LocalClassIsin { get; set; }
    public  ICollection<PcfPublishingDefinitionEntity> PublishingDefinitions { get;  set; }

    public ClassDefinitionEntity()
    {
        PublishingDefinitions = new List<PcfPublishingDefinitionEntity>();
    }
}

And on the many side the PcfPublishingDefinitionEntity class:

public class PcfPublishingDefinitionEntity
{
    public int ClassId { get; set; }
    public ClassDefinitionEntity ClassDefinition { get; set;}
    public PcfFormatEnum Format { get; set; }
    public PcfPublishingChannelEnum Channel { get; set; }
}

My column names do not follow entity conventions so the code in OnModelCreating is like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder){
...
        modelBuilder.Entity<PcfPublishingDefinitionEntity()
           .ToTable("IFM_PCF_PUBLISHING_DEFINITION");
        modelBuilder.Entity<PcfPublishingDefinitionEntity>()
           .HasKey(e => new { e.ClassId, e.Channel, e.Format });
        modelBuilder.Entity<PcfPublishingDefinitionEntity>()
           .Property(e => e.Channel)
           .HasColumnName("PUBLICATION_CHANNEL");
        modelBuilder.Entity<PcfPublishingDefinitionEntity>()
            .Property(e => e.Format)
            .HasColumnName("PUBLICATION_FORMAT");
        modelBuilder.Entity<PcfPublishingDefinitionEntity>()
            .Property(e => e.ClassId)
            .HasColumnName("CLASS_ID");
        modelBuilder.Entity<PcfPublishingDefinitionEntity>()
            .HasRequired(pd => pd.ClassDefinition)
            .WithMany(cd => cd.PublishingDefinitions)
            .HasForeignKey(pd => pd.ClassId);
...
}

But It's not working. The PublishingDefinitions collection is always empty.

What am I doing wrong ?

Standard convention for one-to-many or many-to-many in EF I think is lazy loading meaning you have to tell the db to include the collection when you fetch the data from the db. If you are using linq use .include.

EG:

yourdbcontext.ClassDefinitionEntity.Include(x => x.PublishingDefinitions).ToList(); 

Entity Framework Loading Related Entities

If Lazy Loading is enabled, make sure to include the word virtual to the relationship. This would help EF to load lazily that entity or entities. Please refer to https://docs.microsoft.com/en-us/ef/ef6/querying/related-data for more information about Lazy Loading and how entities are loaded when such functionality is enabled.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM