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)。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...