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 can contain a lot of metadata. When displaying a Document object, I have:

  HasMany<MetadataValue>(x => x.MetadataList) .WithRequired() .HasForeignKey(x => x.DocumentId); 

When I save a Document object, its metadata list is also saved. But when I return the Document object, its metadata list is always zero. What is wrong with this display?

+4
source share
3 answers

Instead of making the navigation property virtual to enable lazy loading - as suggested by Paige Cook, you can also load the collection:

 var query = dbContext.Documents .Where(d => d.Id == "MyDoc") .Include(d => d.MetadataList); 

If you are not using lazy loading, you always need to clearly define in your queries which navigation properties - links and collections - you want to load along with your entity.

+5
source

You need to declare your MetadataList property in your Document class as a virtual ICollection so that EF can correctly display it:

 public virtual ICollection<MetadataValue> MetadataList { get; set; } 
+3
source

The easiest way is to use MetadataValueID as a key (instead of using DocumentID).

+1
source

Source: https://habr.com/ru/post/1347932/


All Articles