EF 4.1 code first: one-to-many mapping problem
In my domain I have these classes (in simplified form)
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; }
}
A document may have many metadata. In mapping of Document entity I have:
HasMany<MetadataValue>(x => x.MetadataList)
.WithRequired()
.HasForeignKey(x => x.DocumentId);
When I persist Document object its metadata list is also persisted. But when I retrieve Document object its metadata list is always null. What is wrong with this mapping?
Instead of making the navigation property virtual
to enable lazy loading - as proposed by Paige Cook - you can also eager load the collection:
var query = dbContext.Documents
.Where(d => d.Id == "MyDoc")
.Include(d => d.MetadataList);
If you don't use lazy loading you always have to define explicitely in your queries which navigation property - references and collections - you want to load together with your entity.
You need to declare your MetadataList property on your Document class as a virtual ICollection so that EF can map it properly:
public virtual ICollection<MetadataValue> MetadataList { get; set; }
The easiest way is to use MetadataValueID as the key (instead of using DocumentID).
精彩评论