rovsen
rovsen

Reputation: 5022

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?

Upvotes: 4

Views: 3604

Answers (3)

prj
prj

Reputation: 11

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

Upvotes: 1

Slauma
Slauma

Reputation: 177133

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.

Upvotes: 5

Paige Cook
Paige Cook

Reputation: 22555

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; }

Upvotes: 3

Related Questions