我尝试使用实体框架代码优先和流畅的api来实现一对多的关系
一方面,我有 ClassDefinitionEntity 类:
public class ClassDefinitionEntity{
public string LocalClassIsin { get; set; }
public ICollection<PcfPublishingDefinitionEntity> PublishingDefinitions { get; set; }
public ClassDefinitionEntity()
{
PublishingDefinitions = new List<PcfPublishingDefinitionEntity>();
}
}
在很多方面 PcfPublishingDefinitionEntity 类:
public class PcfPublishingDefinitionEntity
{
public int ClassId { get; set; }
public ClassDefinitionEntity ClassDefinition { get; set;}
public PcfFormatEnum Format { get; set; }
public PcfPublishingChannelEnum Channel { get; set; }
}
我的列名不遵循实体约定,因此 OnModelCreating 中的代码如下所示:
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);
...
}
但它没有用。 PublishingDefinitions 集合始终为空。
我做错了什么?
答案 0 :(得分:2)
EF中一对多或多对多的标准约定我认为是延迟加载意味着您必须告诉db在从db获取数据时包含该集合。如果您使用linq,请使用.include。
EG:
yourdbcontext.ClassDefinitionEntity.Include(x => x.PublishingDefinitions).ToList();
答案 1 :(得分:0)
如果启用了延迟加载,请确保在关系中包括单词virtual
。这将帮助EF延迟加载该实体。有关延迟加载以及启用此类功能时如何加载实体的更多信息,请参考https://docs.microsoft.com/en-us/ef/ef6/querying/related-data。