I have an MVC.NET application with a number of models, some of which include classes with these properties:
public class Species
{
[Key]
public int SpeciesID { get; set; }
public string SpeciesName { get; set; }
public virtual List<Photo> Photos { get; set; }
}
public class Photo
{
[Key]
public Guid PhotoID { get; set; }
public int? SpeciesID { get; set; }
[ForeignKey("SpeciesID")]
public virtual Species Species { get; set; }
}
Users can upload photos and tag them with species. One species can have multiple photos. One photo can only have one species. Accessing the Photos property of the Species class automatically loads all photos of the species as expected. What I'm trying to do now is add the following to the Species class:
public Guid? DefaultPhotoID { get; set; }
[ForeignKey("DefaultPhotoID")]
public virtual Photo DefaultPhoto { get; set; }
This allows users to select a default photo for the species. This also works and the DefaultPhoto property is automatically populated based on the DefaultPhotoID property. However as soon I add the above code the Photos property of a Species class stops returning anything. I thing this is related to the fact that the Species class now has two virtual properties of Photo type (a single photo and a collection of photos) and for some reason doesn't know how to handle the collection anymore. Does anyone have an idea why it's breaking and how to fix it? To be more specific - I also have other models, which form a hierarchy (order->family->genus->species), which also work correctly until the DefaultPhoto property is added.
EDIT: To better explain the problem I have uploaded a simplified version of the project with just the hierarchy of the classes here: http://www.speedyshare.com/dgCJw/MvcTest-VirtualProperty.zip
It currently has a DB with 4 photo items and if you go to the Index view of any of the models (Orders, Families, Species etc.) you will see the total number of photos is displayed correctly.
However if you add the DefaultPhotoID and DefaultPhoto properties to the BaseModel (just uncomment the existing code) these numbers will not be displayed anymore (they will be 0).
I hope that explains the problem - I want to use the Photos property without the need to run custom queries to populate it.