Hnus
Hnus

Reputation: 969

ASP .NET model within itself

Can I have model class within itself? It seems it works but every time I tried to retrive the document in controller the SimilarDocuments field was always null then after googling I found a work around instead of Document document = db.Documents.Find(id)I use Document document = db.Documents.Include("SimilarDocuments").FirstOrDefault(x => x.ID == id) but something tells me its not a ideal way how to approach this problem. Why simple .Find(id)didnt work?

Here is simplified version of my model:

public class Document
{
    public int ID { get; set; }

    public ICollection<Document> SimilarDocuments { get; set; }

    public Document()
    {
        SimilarDocuments = new List<Document>();
    }
}

Upvotes: 0

Views: 83

Answers (2)

TGlatzer
TGlatzer

Reputation: 6248

You are expecting the NavigationProperty to be lazy-loaded. This will not happen automatically, if you do not mark the ICollection<EntityType> as virtual.

When you change that and make it virtual (and you do not explicitly deactivate lazy-loading somewhere else in code), it will load the data on demand - as long as your DBContext is opened.

public class Document {
  public virtual ICollection<Document> SimilarDocuments { get; set; }
}

Here you can read more about the topic of lazy-loading and eager-loading: http://msdn.microsoft.com/en-us/data/jj574232.aspx

Upvotes: 1

ymz
ymz

Reputation: 6914

because when Find methos is invoked from db.Documents it search in every Document element. your serach aim to search inside a field for each document and that is why you should use Include("SimilarDocuments")

  • Documents
    • Document -> this is where db.Documents.Find search
      • SimilarDocuments --> you want to search here

Upvotes: 0

Related Questions