I have the scenario where a user can upload multiple photos (One-to-Many). The user also can have a default photo (One-to-One). However, I entity framework core 2.0 tells that he cannot recognize the relationship when I use the following code:
public class User
{
public Guid Id { get; set; }
public ICollection<Photo> Photos{ get; set; }
public Photo DefaultPhoto { get; set; }
[ForeignKey("DefaultPhoto")]
public Guid DefaultPhotoId { get; set; }
}
public class Photo
{
public Guid Id { get; set; }
public User Owner { get; set; }
}
How may I achieve these multiple relationships?
There error shown by EF-Core:
System.InvalidOperationException: 'Unable to determine the relationship represented by navigation property 'Photo.Owner' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'
UPDATE:
Adding [InverseProperty("Photos")] to the navigation property Owner in File Model seems to be working. I am not sure if that is the correct way?
In this image File=Photo; Uploader=Owner (to be comparable with the above model).
UPDATE 2:
I confirm what @Ivan said in the comments, with DataAnnotation approach, I get One-to-Many in two directions instead of One-to-Many and One-to-One. This figure shows the generated database by using InverseProperty (the connection between the to entities show the bi-directional One-to-Many relationship):
In this image File=Photo; Uploader=Owner (to be comparable with the above model).

Photoswith [InverseProperty("Owner")]` you tell that another end of navigation property Photos in class User is propertyOwnerin classPhoto. Same can be done in reverse. If you markOwnerwith[InverseProperty("Photos")]- you are doing the same. Why it works one way and not the other for you - I'm not sure.OwnerId) was declared as nullable. I wonder what would happen indeed when you try to insert into your current database.InversePropertysolves just half of the problem - correctly relating one-to-many relationship defining navigation properties. However the second relationship by convention is one-to-many, not one-to-one as desired. Forget about data annotations, fluent configuration is a must.Photo DefaultPhotoinUseris something likeICollection<User> DefaultPhotoUsersinPhoto, or in other words - one to many. There is no way to configure it as one to one using data annotations, hence you should use fluent API (as in @gldraphael answer).