EF 4.1代码优先:一对多映射问题

| 在我的域中,我有这些类(以简化形式)
    public class Document
    {    
        public string Id { get; set; }
        public IList<MetadataValue> MetadataList { get; set; }
    }

    public class MetadataValue
    {
        public string DocumentId { get; set; }
        public string Metadata { get; set; }
        public string Value { get; set; }
    }
一个文档可能有许多元数据。在文档实体的映射中,我有:
    HasMany<MetadataValue>(x => x.MetadataList)
        .WithRequired()
        .HasForeignKey(x => x.DocumentId);
当我保留Document对象时,其元数据列表也将保留。但是,当我检索Document对象时,其元数据列表始终为null。此映射有什么问题?     
已邀请:
除了像Paige Cook所建议的那样,使导航属性
virtual
启用延迟加载,您还可以渴望加载集合:
var query = dbContext.Documents
    .Where(d => d.Id == \"MyDoc\")
    .Include(d => d.MetadataList);
如果不使用延迟加载,则始终必须在查询中显式定义要与实体一起加载的导航属性(引用和集合)。     
您需要在Document类上将MetadataList属性声明为虚拟ICollection,以便EF可以正确映射它:
public virtual ICollection<MetadataValue> MetadataList { get; set; }
    
最简单的方法是使用MetadataValueID作为键(而不是使用DocumentID)。     

要回复问题请先登录注册