webpat
webpat

Reputation: 1949

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 ?

Upvotes: 1

Views: 4385

Answers (2)

Victor LG
Victor LG

Reputation: 646

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://learn.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.

enter image description here

Upvotes: 1

Mathias Marin
Mathias Marin

Reputation: 106

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

Upvotes: 6

Related Questions