Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
rovsen Avatar asked Jan 20 '23 00:01

rovsen


1 Answers

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.

like image 75
Slauma Avatar answered Jan 31 '23 12:01

Slauma